Display numerical solution of PDE as a movie in Matlab

graphing-functionsMATLABnumerical methodspartial differential equations

Investigate numerically whether the FCTS scheme
$$
u_k^{n+1} = u_k^n – \frac{a\Delta t}{2\Delta x} \left( u_{k+1}^n – u_{k-1}^n\right) + \frac{\nu\Delta t}{\Delta x^2} \left( u_{k+1}^n – 2 u_k^n + u_{k-1}^n\right)
$$

can be used for the advection-diffusion equation $v_t + av_x = \nu v_{xx}$. Use a sharp Gaussian-like initial condition (see numerical code that tests the advection equation), $a=1$, $x\in (-5,15)$, 500 mesh intervals, $\Delta t = \min (0.75 \Delta x^2/(2\nu), 0.75 \Delta x/a)$, and compute the solution at $t=10$. Does it break if the diffusion coefficient is small?

Im trying to solve this problem and here is my code:

clc;
clear;

%%%Variables%%%%%

xmin=-5;
xmax=15;
N=100; %Number of nodes-1
t=0;
tmax=10;
umax=100;
v=0.05;

%%%%%discretise the domain/time%%%%%
dx=(xmax-xmin)/N;
dt= min([0.75*(dx^2/(2*v)) 0.75*dx]);
x = xmin:dx:xmax;

%%%%%Initial Conditions%%%%%%
F = @(x) umax*exp(-x.^2*10.0);
u0 = F(x);

u=u0;
unp1=u;

timesteps = ceil(tmax/dt);

for n=1:timesteps
    for i=2:N
        unp1(i) = u(i) - dt/(2*dx)*(u(i+1)-u(i-1))+(v*dt)/(dx^2)*(u(i+1)-2*u(i)+u(i-1));
    end
    u=unp1;
    t=t+dt;
    plot(x,u)
end

My question is, is there way to plot for a movie for difference values of $v$? at tmax? Also, is my code correctly implemently with the scheme?

Best Answer

The code looks correct, but the problem statement specifies N=500 instead. Here is the desired Matlab code

%%%%%Initial Conditions%%%%%%
F = @(x) umax*exp(-x.^2*10.0);
u0 = F(x);

u=u0;
unp1=u;

figure;
hp=plot(x,u);
ht=title(strcat('t = ',num2str(t)));
xlim([xmin xmax]);
ylim([0 umax]);

timesteps = ceil(tmax/dt);

for n=1:timesteps
    for i=2:N
        unp1(i) = u(i) - dt/(2*dx)*(u(i+1)-u(i-1))+(v*dt)/(dx^2)*(u(i+1)-2*u(i)+u(i-1));
    end
    u=unp1;
    t=t+dt;
    set(hp,'YData',u);
    set(ht,'String',strcat('t = ',num2str(t)));
    drawnow;
end

with the following output

output

Related Question