How to change this code to 3D wave propagating animation?

2 views (last 30 days)
When I run this code, I cannot get wave propagation animation. Can any professional give me a hand? Thanks very much.
clear all; clc;
A = 0.1; k = 1; w = 3; phi = 15;
x0 = 0; dx = 0.1; xf = 20; x = [x0:dx:xf];
t0 = 0; dt = 0.1; tf = 20; t = [t0:dt:tf];
path = 'G:\My Drive\Animation\'; frameRate2 = 840*630;
for i = 1:length(t)
y_tx(:,i) = 2*A.*cos(phi/2).*sin(k.*x(i)-w.*t+phi/2);
[X,Y] = meshgrid(y_tt(i,:));
end
videoWriter = VideoWriter([path, '3D constructive and destructive interference','.mp4']);
videoWriter.FrameRate = frameRate2;
open(videoWriter);
figure();
for i = 1: length(t)
surf(t,x,y_tt)
xlabel('Time'); ylabel('Space');
out = getframe(gcf); videoWriter.writeVideo(out);
end
videoWriter.close();

Accepted Answer

Voss
Voss on 12 Feb 2022
Your y_tt is a 2D matrix, with one dimension corresponding to time and one dimension corresponding to x, a spatial dimension presumably. I redefined it here to make it 3D (not sure if it's what was intended but it was a natural redefinition, giving it two spatial dimensions over which it is identical in each dimension).
Also note that the code in your final loop to get the frames of the video does not depend on i, so nothing would change each frame - no animation. Now the 3D matrix has time as the third dimension and you can make surfaces out of 2D slices of it to get an animation. Again, I have no idea if this is what you're after, but it's a 3D animation.
(Also the frame rate seemed pretty high so I dropped it way down.)
clear all; clc;
A = 0.1; k = 1; w = 3; phi = 15;
x0 = 0; dx = 0.1; xf = 20; x = [x0:dx:xf];
t0 = 0; dt = 0.1; tf = 20; t = [t0:dt:tf];
path = 'G:\My Drive\Animation\';
% frameRate2 = 840*630;
frameRate2 = 60;
% for i = 1:length(t)
% y_tt(:,i) = 2*A.*cos(phi/2).*sin(k.*x(i)-w.*t+phi/2);
% [X,Y] = meshgrid(y_tt(i,:));
% end
[x1,x2] = meshgrid(x,x);
t = reshape(t,[1 1 numel(t)]);
y_tt = 2*A.*cos(phi/2).*(sin(k.*x1-w.*t+phi/2)+sin(k.*x2-w.*t+phi/2));
videoWriter = VideoWriter([path, '3D constructive and destructive interference','.mp4']);
videoWriter.FrameRate = frameRate2;
open(videoWriter);
figure();
for i = 1:numel(t)
% surf(t,x,y_tt)
% xlabel('Time'); ylabel('Space');
% out = getframe(gcf); videoWriter.writeVideo(out);
surf(x,x,y_tt(:,:,i),'EdgeColor','none');
xlabel('Space'); ylabel('Space'); zlabel('Amplitude');
videoWriter.writeVideo(getframe(gcf));
end
videoWriter.close();
  1 Comment
yunya liu
yunya liu on 12 Feb 2022
Really appreciate that! You're correct that y_tt is a 3D matrix hence surfaces can be obtained by slicing. Really helpful.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!