MATLAB: How to conditionally solve two ODEs simultaneously using ‘if-else’

acceleration performanceelectric vehicleif elseMATLABode45velocity vs time plot

Hello there,
I'm modeling acceleration performance of an electric vehicle (i.e velocity vs time plot).
I have two conditions:
1. For velocity less than 39.9 m/s, the velocity will be calculated by this ODE: dv/dt= 9.513-(0.00032*v^2)
2. For velocity greater than or equal to 39.9 m/s, the velocity will be calculated by this ODE: dv/dt= 13.43-(0.922*v)-(0.00032*v^2).
The solution of these ODEs should give me a plot of velocity Vs. time. I tried ode45 & if-else loop for this code, but the code only solves 1st ODE and directly jumps to plotting the results without solving for the 2nd condition. Hence I'm getting a top speed of 615km/h, which is not a correct value.
I request, please guide me through this problem.
Thank you.
clc; clear all;
tspan = linspace(0,50,501); %time in s
v=0;
if v<39.9 %velocity in m/s
[t,v] = ode45(@(t,v) 9.513-(0.00032*v.^2), tspan, v);
elseif v>=39.9
[t,v] = ode45(@(t,v) 13.43-(0.922*v)-(0.00032*v.^2), tspan, v);
end
kph=v*3.6; %converting m/s to km/h
plot(t,kph)
xlabel('time S')
ylabel('speed kph')

Best Answer

ode45 does not check its values between start and end time. That is why you need to write your own solver or include the ifelse inside your function. I wrote the latter below.
function vd = fun1(t,v)
if v <39.9
vd = 9.513-(0.00032*v.^2);
elseif v >= 39.9
vd = 13.43-(0.922*v)-(0.00032*v.^2);
end
end
Then in the main script, you call
tspan = linspace(0,50,501); %time in s
v=0;
[t,v] = ode45(@fun1, tspan, v);