Solving a system of ODEs with conditionally defined coefficient

Hi, I want to plot on the interval the solution of the following system of ODEs
with the initial conditions
,
where
.
I wrote the function, by defining the coefficient f, using "piecewise" sintax:
function dzdt=odefunw1(t,z)
syms t
f=piecewise(0<=t<1, -2*t^2+3*t, t>=1, 1/t);
dzdt=zeros(2,1);
dzdt(1)=z(2);
dzdt(2)=z(1)-f*z(2);
end
In the Command Window, I wrote
tspan = [0 1000];
z0 = [0.1 0.1];
[t,z] = ode45(@(t,z) odefunw1(t,z), tspan, z0);
plot(t,z(:,1),'g',t,z(:,2),'b')
But several errors occured. Where do I wrong and how could I fix it? Thanks in advance.

 Réponse acceptée

replace
f=piecewise(0<=t<1, -2*t^2+3*t, t>=1, 1/t);
with
if t >= 1
f = 1/t;
else
f = -2*t^2+3*t;
end

3 commentaires

Cris19
Cris19 le 15 Déc 2019
Modifié(e) : Cris19 le 15 Déc 2019
Thank you for the answer, but it's not working.
I wrote the function
function dzdt=odefunw1(t,z)
syms t
if t >= 1
f = 1/t;
else
f = -2*t^2+3*t;
end;
dzdt=zeros(2,1);
dzdt(1)=z(2);
dzdt(2)=z(1)-f*z(2);
end
and the commands
tspan = [0 100];
z0 = [0.1 0.1];
[t,z] = ode45(@(t,z) odefunw1(t,z), tspan, z0);
plot(t,z(:,1),'r',t,z(:,2),'b')
and the following errors occured:
Conversion to logical from sym is not possible.
Error in odefunw1 (line 3)
if t >= 1
Error in @(t,z)odefunw1(t,z)
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin)
You are overwriting t variable. Remove this line:
syms t
It worked! Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by