Can anyone check my code for ode45 function question?

function dz=f2(t,z)
dz=[z(1)-z(2)^2*z(1)-z(2); z(1)];
t=[0 20];
initz=[1; 1];
[t,z]=ode45(@f2, t, initz);
plot(t, z(:,2))
Is my solution correct?

 Accepted Answer

Just noticed it you need to reduce your second order to first order to ode as below:
syms y(t)
ode1=diff(y,2) == 1-y^2;
ode2=diff(y,1) == y;
vars = y(t)
V = odeToVectorField([ode1,ode2])
M = matlabFunction(V,'vars', {'t','Y'})
interval = [0 5]; %time interval
y0 = [1 1]; %initial conditions
ySol = ode45(M,interval,y0);
tValues = linspace(interval(1),interval(2));
yValues = deval(ySol,tValues,1); %number 1 denotes first solution likewise you can mention 2 solution
plot(tValues,yValues,'-')
figure
yValues = deval(ySol,tValues,2);
plot(tValues,yValues,'-or')
Screen Shot 2018-12-16 at 5.09.56 PM.png
Screen Shot 2018-12-16 at 5.10.35 PM.png

2 Comments

Thanks! I should change your interval to [0 20]
Anytime :) , yes you are right.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!