Trying to plot linear and non-linear hard spring oscillations on same plot
Here is my code:
function PartB
m = 2; k = 2; epsilon = -4;
omega0 = sqrt(k/m); omega = epsilon / m;
param = [omega0,omega];
t0 = 0; y0 = 2; v0 = 0; Y0 = [y0;v0]; tf = 12;
options = odeset('AbsTol',1e-10,'relTol',1e-10);
[t,Y] = ode45(@f,[t0,tf],Y0,options,param);
y = Y(:,1); %v = Y(:,2);
m = 2; k = 2; epsilon = 0;
omega = epsilon / m;
param = [omega0,omega];
t0 = 0; y0 = 2; v0 = 0; Y0 = [y0;v0]; tf = 12;
options = odeset('AbsTol',1e-10,'relTol',1e-10);
[tt,YY] = ode45(@f,[t0,tf],Y0,options,param);
y2 = YY(:,1); %v2 = YY(:,2);
figure(1)
plot(t,y,'b','LineWidth',2)
hold on; grid on;
plot(t,y2,'b','LineWidth',2) %position with respect to Y
ylabel('y, yy'); xlabel('t'); grid on;
legend('\epsilon = -4','\epsilon = 0')
%----------------------------------------------------------------
function dYdt = f(~,Y,param)
y = Y(1); v = Y(2);
omega0 = param(1); omega = param(2);
dYdt = [ v ; - omega0^2*y + omega*y^3 ];
I keep getting the error:
>> PartB
Error using plot
Vectors must be the same length.
Error in PartB (line 19)
plot(t,y2,'b','LineWidth',2) %position with respect to Y
I know that y and y2 are different sizes but I can't seem to get these plots on the same plot. How do I fix this?

 채택된 답변

Torsten
Torsten 2018년 4월 17일

0 개 추천

t0 = 0; y0 = 2; v0 = 0; Y0 = [y0;v0]; tf = 12; deltat = 0.1; tspan=t0:deltat:tf;
...
[t,Y] = ode45(@(t,y)f(t,y,param),tspan,Y0,options);
...
t0 = 0; y0 = 2; v0 = 0; Y0 = [y0;v0]; tf = 12; deltat = 0.1; tspan=t0:deltat:tf;
...
[tt,YY] = ode45(@(t,y)f(t,y,param),tspan,Y0,options); 
...

Best wishes

Torsten.

추가 답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2018년 4월 12일
편집: KALYAN ACHARJYA 2018년 4월 12일

0 개 추천

As one parameter is common "t". Create two y-axis for the different length plots. Check the following link
https://in.mathworks.com/help/matlab/creating_plots/plotting-with-two-y-axes.html
% For Example
t=linspace(0,25);
y=sin(t/2);
yyaxis left
plot(t,y);
y1=t.^2/2;
yyaxis right
plot(t,y1);

댓글 수: 1

Ok thank you! However, is there any way to modify the vectors to be the same length to get both of the ODE's on the Y axis

댓글을 달려면 로그인하십시오.

카테고리

질문:

2018년 4월 12일

댓글:

2018년 4월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by