# Solving a system of ODEs with conditionally defined coefficient

2 views (last 30 days)
Cris19 on 15 Dec 2019
Commented: Cris19 on 15 Dec 2019
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.

darova on 15 Dec 2019
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

Cris19 on 15 Dec 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)
darova on 15 Dec 2019
You are overwriting t variable. Remove this line:
syms t
Cris19 on 15 Dec 2019
It worked! Thank you very much!