Saurav Agarwal
Saurav Agarwal

Reputation: 43

3d plot of wave function

How can I plot the wave function n=a*cos(k*x-w*t) in Matlab in 3D with simulation? The code I used was:

k=0.05;
f=100;
w=2*pi*f;
a=1;
x=[-5:1:5];
t=[0:2:20];
n=a.*cos(k.*x-w.*t);
surf(x,t,n);

Upvotes: 0

Views: 2254

Answers (2)

jkazan
jkazan

Reputation: 1199

In this example I have made the resolution better by adding points to x and t. In the animation I have changed the value for k, you can also change e.g. f.

Example

f=100;
w=2*pi*f;
a=1;
x=linspace(-5,5,50);
t=linspace(0,2,50);


for k = 0.05:0.01:2         % Change values of e.g. k
    n = a.*cos(k.*x-w.*t);  % Re-calculate n
    pause(0.02)             % pause to control animation speed
    s = surf(x,t,repmat(n,[length(t),1])); % Use repmat to make Z 2D
    title(['k = ',num2str(k)])

    % Just some nice settings for surf plot
    shading interp
    lighting phong
    camlight left; camlight right; camlight left; camlight right;
    colormap copper
    alpha(.8)
end

Upvotes: 0

Ander Biguri
Ander Biguri

Reputation: 35525

To plot a surface you need a mesh of data. The x,t you created are just a line, there is just a single t for every x, but a surface has multiple t for every x.

If you change your definition of x and t to:

[x,t]=meshgrid(-5:1:5,0:2:20);

Your code runs and plots:

enter image description here

Upvotes: 2

Related Questions