MATLAB: How to create a 3D surface plot of a function y that depends on x and t

computational physicssimulinkwave propagationwaves

I need to create a surface plot of a wave that depeneds on x and t where the time axis covers at least 1.2 times the period of the wave. My code so far for the initial waveform and propagation of said wave can be seen below
close all;
clc;
L = 1.0; %string length
Nx = 100; %steps in x
Nt = 100; %steps in t
u = zeros(Nx,Nt);
c = sqrt(30000); % speed, calculated from c^2 = (T/mu)
r = 0.8;
sigma = 0.04;
x_bar = 0.4;
y_max = 0.2;
dx = L/Nx;
dt = (r*dx)/c;
x = linspace(0,L,Nx);
t = linspace(0, Nt*dt,Nt); %total time = # of steps * time step (Nt*dt)
y = y_max*exp(-(x-x_bar).^2/(2*sigma.^2)); %%%%%%%% initial waveform beginning at x = 0.4 %%%%%%%%%%%%%
u(:,1) = y;
u(:,2) = y;
for n = 2 : Nt-1 % x position; starts at n=2 because array indices must
% be positive integers and thus n-1 = 0 is not allowed
% for n=1
for i = 2 : Nx-1 % x position; starts at i=2 because array indices must
% be positive integers and thus i-1 = 0 is not allowed
% for i=1
u(i,n+1) = 2*(1-r.^2)*u(i,n) - u(i,n-1)+r.^2*(u(i+1,n) + u(i-1,n)); %%%%%% this line propogates the wave as time goes on %%%%%%
end
% boundary conditions, both ends fixed ( y = 0)
u(1,n+1) = 0;
u(Nx,n+1) = 0;
end
set(gcf,'units','normalized','position',[0.5,0.1,0.4,0.7]);
grid on;
col = 'b'; LW = 2, fs = 14;
subplot(5,1,1)
xP = x,yP = u(:,1)';
plot(xP,yP,col,'linewidth',LW);
grid on; box on;
ylabel('y');
title('Initial Gaussian pluck for r=0.8')
axis([0 L -0.4 0.4])
subplot(5,1,2)
xP = x,yP = u(:,round(Nt/10))';
plot(xP,yP,col,'linewidth',LW);
grid on; box on;
ylabel('y');
title('Waves spreading from initial position like when r=1');
axis([0 L -0.4 0.4])
subplot(5,1,3)
xP = x,yP = u(:,round(Nt/2))';
plot(xP,yP,col,'linewidth',LW);
grid on; box on;
ylabel('y');
% title('Waves moving more slowly over same amount of time');
axis([0 L -0.4 0.4])
subplot(5,1,4)
xP = x,yP = u(:,round(2*Nt/3))';
plot(xP,yP,col,'linewidth',LW);
grid on; box on;
ylabel('y');
title('Waves moving more slowly over same amount of time');
axis([0 L -0.4 0.4])
subplot(5,1,5)
xP = x,yP = u(:,Nt)';
plot(xP,yP,col,'linewidth',LW);
grid on; box on;
ylabel('y');
%title('Wave portions come together inverted and at x=0.6');
axis([0 L -0.4 0.4])

Best Answer

[T, X] = meshgrid(t,x);
surf(X,T,u)
xlabel('X axis')
ylabel('Time')