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

조회 수: 4 (최근 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개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by