How to conditionally solve two ODEs simultaneously using 'if-else' ?

2 ビュー (過去 30 日間)
Sagar Dhuri
Sagar Dhuri 2018 年 9 月 6 日
コメント済み: Sagar Dhuri 2018 年 9 月 7 日
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')

採用された回答

Aquatris
Aquatris 2018 年 9 月 7 日
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);
  1 件のコメント
Sagar Dhuri
Sagar Dhuri 2018 年 9 月 7 日
Dear Aquatris,
Thanks you very much for your help. i really appreciate it.
This code sorted out the issue completely.

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by