Beijing Institute of Technology | Ming-Jian Li
The following MATLAB code is a companion code for the course on Artificial Intelligence and Simulation Science. It is designed to calculate the evolution process of an electromagnetic pulse using the Finite-Difference Time-Domain (FDTD) method.
x1% 1D FDTD simulation with pulse
2clear;
3ke = 100;
4% Position of the source
5ks = 1;
6% ks = ke / 2;
7% Number of time steps
8nsteps = 2000;
9% Cell size and time stepping
10c0 = 3.e8;
11dx = 0.01;
12dt = dx / (2 .* c0);
13% Constants
14cc = c0 * dt / dx;
15% Initialize vectors
16ex = zeros(1, ke);
17hy = zeros(1, ke);
18% Gaussian pulse
19t0 = 20;
20spread = 8;
21% Gaussian signal
22for t = 1:nsteps
23 time(t) = t;
24 ex_source(t) = exp(- .5 * ((t - t0) / spread) ^ 2);
25end
26plot(time,ex_source)
27
28% Start loop
29M = moviein(nsteps);
30
31for t = 1:nsteps
32 % E field loop
33 for k = 2:ke - 1
34 ex(k) = ex(k) + cc * (hy(k - 1) - hy(k));
35 end
36
37 % Source
38 ex(ks) = exp(- .5 * ((t - t0) / spread) ^ 2);
39 % H field loop
40 for k = 1:ke - 1
41 hy(k) = hy(k) + cc * (ex(k) - ex(k + 1));
42 end
43
44 plot(ex); axis([1 ke -2 2]);
45 % plot(hy); axis([1 ke -2 2]);
46 M(:, t) = getframe;
47end
The result is as follows.