MATLAB: Won’t this plot

plotvelocity

I'm new to Matlab and I'm trying to plot the velocity related to the function for a damped harmonic oscillator. I have been able to plot the function itself, but when I try to plot the velocity of said function, I receive this error:
Error using plot
Vectors must be the same length.
Error in damped_oscillator (line 102)
plot(t,v);
I'm not sure how to solve this problem. I've linked the original code. Any help is much appreciated!

Best Answer

You can make the privious three plot in single description using for loop, define "a" in array. #Recomended. The error arises because of non equal length of t and v, as v result from diff. Hence I have ignored the last element of t to make them both equal. You can opt out the first one also, as per your requirements.
m=20; %Mass
k=30; %Spring constant
c=0.9; %Damping constant






A=1;
a=0;
g=c/(2*m); %Damping coefficient






wn=sqrt(k/m); %Natural frequency






wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency






t=linspace(0,40,1000); %Time value







x=A*exp(-g*t).*cos(wd*t-a); %x(t)







subplot(4,3,1),plot(t,x)
title('Question 1')
xlabel('Time')
ylabel('Displacement (m)');
grid on;
c=0.9; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,20,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,1),plot(t,x)
title('Question 2')
xlabel('Time (s)')
ylabel('Displacement (m)')
grid on;
c=0; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,40,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,2),plot(t,x)
title('Question 3')
xlabel('Time (s)')
ylabel('Displacement (m)')
grid on;
c=1; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,40,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,3),plot(t,x)
c=5; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,40,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,4),plot(t,x)
c=15; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,40,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,5),plot(t,x)
c=50; %Damping constant
A=1;
a=0;
g= c/(2*m); %Damping coefficient
wn=sqrt(k/m); %Natural frequency
wd=sqrt(((wn)^2)-(g)^2); %Damped natural frequency
t=linspace(0,40,1000); %Time value
x=A*exp(-g*t).*cos(wd*t-a); %x(t)
subplot(4,2,6),plot(t,x)
legend('0','1','5','15','50')
t=linspace(0,40,1000); %Time value
x=A*exp(-g.*t).*cos(wd.*t-a); %x(t)
v=diff(x)./diff(t); %Velocity
subplot(4,2,7),plot(t(1:end-1),v);