problem plotting 2d FDM wave equation simulation

clear
clc
close all
VL = 2;
tMin = 0;
tMax = 30;
xMin = -10;
xMax = 10;
yMin = -10;
yMax = 10;
Nt = 100;
Nx = 100;
Ny = 100;
t = linspace(tMin,tMax,Nt);
x = linspace(xMin,xMax,Nx);
y = linspace(yMin,yMax,Ny);
DeltaT = t(2) - t(1);
DeltaX = x(2) - x(1);
DeltaY = y(2) - y(1);
CFX = ((VL)*(DeltaT/DeltaX))^2;
CFY = ((VL)*(DeltaT/DeltaY))^2;
u = zeros(Nt,Nx,Ny);
[X,Y] = meshgrid(x,y);
u(1,:,:) = Initial(t(1),X,Y);
u(2,:,:) = Initial(t(1),X,Y) + InitialV(t(1),X,Y);
for i=3:Nt
for j=1:Nx
for k=1:Ny
if(j==1 || j==Nx || k==1 || k==Ny)
u(i,j,k) = 0;
else
u(i,j,k) = 2*u(i-1,j,k) - u(i-2,j,k) + (CFX)*(u(i-1,j+1,k) - 2*u(i-1,j,k) + u(i-1,j-1,k)) + (CFY)*(u(i-1,j,k+1) - 2*u(i-1,j,k) + u(i-1,j,k-1));
end
end
end
end
function [p] = Initial(t,x,y);
p = exp(-(x.^2.)-(y.^2.));
%%%%%%%%%%%%%%%%
function [g] = InitialV(t,x,y);
g = 0;
Hi!
I am trying to make a finite difference simulation of the 2d wave equation. I succeeded in finding all the function values for a given time and position, however I am struggling to make the (animated) plot. The time domain is divided into Nt steps and the same was done for x and y (Nx and Ny steps). Initial(t,x,y) is u(t=0,x,y) and InitalV is ut(t=0,x,y).
Could someone please tell me how I can make the plot or how I can link the matrix values of u(i,j,k) to the x and y values?
Any help is greatly appreciated!

Answers (1)

Read about surf / plot.
[nx,ny,nz] = size(u) ;
for i = 1:t
pcolor(X,Y,u(:,:,i)) ;
drawnow
end

2 Comments

Thanks for your quick response!
I tried your code but it displays a 2d plane with the correct dimensions however not a correct image of the actual numerical solution.
The "surf" function is known to me. I tried this multiple times but I always get the following error:
Z must be a matrix. (when i put "u(i,:,:)" as the Z value)
I know that Z must be a matrix. When I choose a value for i then the result should be a matrix.....
This is what I dont understand, why does it say it must be a matrix when u(i,:,:) is a matrix?
To convert it into a matrix use:
Z = squeeze(u(i,:,:))

Sign in to comment.

Products

Asked:

on 3 Feb 2021

Commented:

on 4 Feb 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!