MATLAB: Can’t Plot These Two ODE’s On Same Plot

errorfunctionode45plot

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?

Best Answer

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.