Reputation: 23
I am trying to make an animation of the 2d wave equation in MATLAB (R2020a). So far I believe that the finite difference method is implemented correctly. However; when I try to plot these values using the "surf" command in matlab it does not work. This is my script so far:
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
the functions: Initial and initialV are u(0,x,y) and ut(0,x,y) respectively. I believe this code works for finding the function values for u however when I try to plot the results as follows:
for i=1:Nt
figure
clf
hold on
surf(X,Y,u(i,:,:))
end
I get an error saying Z must be a matrix... In my opinion this seems strange, slicing a 3d array results in a 2d matrix. How can I make an animation that shows u as a function of x and y? Thanks in advance! any help is greatly appreciated
P.S. I am new to this page so if I am neglecting certain guidelines when it comes to sharing code please let me know and I will adjust it.
Upvotes: 2
Views: 549
Reputation: 1163
Another way to remove the singleton dimension of your u
array would be to use squeeze()
as it doesn't need any information on the remaining size of the array.
for i = 1:Nt
figure
clf
hold on
surf(X, Y, squeeze(u(i, :, :)))
end
Upvotes: 2
Reputation: 4757
To force u(i,:,:)
to match the 100 by 100 dimensions of X
and Y
try using the reshape()
function.
for i=1:Nt
figure
clf
hold on
surf(X,Y,reshape(u(i,:,:),[100 100]));
end
Upvotes: 1