------------------- MATLAB CODE ----------------------
clear
close all
clc
dx = 1;
x = 0:dx:40;
% x will be the row direction
% t will be column direction
% BACKWARD DIFFERENCE IN TIME AND FORWARD DIFFERENCE IN SPACE
for c = [1,0.6,0.3]
dt = c*dx;
t = 0:dt:18;
u_a = zeros(length(x),length(t));
u_a(:,1) = sin(2*pi*x/40);
A = zeros(length(x)-2);
for i = 1:length(x)-2
if i == 1
A(1,1:2) = [1 c/2];
elseif i == length(x)-2
A(end,end-1:end) = [-c/2 1];
else
A(i,i-1:i+1) = [-c/2 1 c/2];
end
end
for i = 2:length(t)
b = u_a(2:end-1,i-1); % here we can add boundary values, in our case (0)
u_a(2:end-1,i) = A\b;
end
figure;contourf(u_a)
title(['Backward(in t),Forward(in x) c = ' num2str(c)])
xlabel('t')
ylabel('x')
end
% LAX SCHEME
for c = [1,0.6,0.3]
dt = c*dx;
t = 0:dt:18;
u_b = zeros(length(x),length(t));
u_b(:,1) = sin(2*pi*x/40);
for it = 2:length(t)
for ix = 2:length(x)-1
u_b(ix,it) = 0.5*(u_b(ix+1,it-1)+u_b(ix-1,it-1))...
- 0.5*c*(u_b(ix+1,it-1)-u_b(ix-1,it-1));
end
end
figure;contourf(u_b)
title(['Lax scheme, c = ' num2str(c)])
xlabel('t')
ylabel('x')
end
% LAX - WENDROFF SCHEME
for c = [1,0.6,0.3]
dt = c*dx;
t = 0:dt:18;
u_c = zeros(length(x),length(t));
u_c(:,1) = sin(2*pi*x/40);
for it = 2:length(t)
for ix = 2:length(x)-1
u_c(ix,it) = u_c(ix,it-1) - 0.5*c*(u_c(ix+1,it-1)-u_c(ix-1,it-1))...
+ 0.5*(c^2)*(u_c(ix+1,it-1)-2*u_c(ix,it-1)+u_c(ix-1,it-1));
end
end
figure;contourf(u_c)
title(['Lax - Wendroff scheme, c = ' num2str(c)])
xlabel('t')
ylabel('x')
end
-------------------------- CODE ENDS ------------------------
Comments
Leave a comment