How to use ode45 with initial conditions defined in script?

6 次查看(过去 30 天)
Hello, I am using ode45 to solve a differential equation. Here is the function file:
.m
function TempP=primary(Tp,y)
hp=13.64;
Tw=25;
mp=0.007;
Cp=1005;
TempP=-2*hp*(Tp-Tw)/(mp*Cp);
Now I have code in script: demo.m
clear all
yrange=[0:0.02:0.9];
Tp=40;
[Tp,y]=ode45(@primary,yrange,Tp);
figure(1)
plot(Tp,y)
ylabel('Tp (deg C)')
xlabel ('Y (m)')
If you can notice, the variables hp,Tw,mp,Cp are defined in primary.m but what I want is, to define in them in demo.m This will help me to control the initial conditions when I have such more function .m files. Is that possible?

回答(2 个)

Star Strider
Star Strider 2016-9-17
You can easily pass your parameters to ‘primary’ from ‘demo’:
function TempP=primary(Tp,y,hp,Tw,mp,Cp)
TempP=-2*hp*(Tp-Tw)/(mp*Cp);
end
hp=13.64;
Tw=25;
mp=0.007;
Cp=1005;
yrange=[0:0.02:0.9];
Tp0=40;
[Tp,y]=ode45(@(Tp,y) primary(Tp,y,hp,Tw,mp,Cp),yrange,Tp0);
figure(1)
plot(Tp,y)
ylabel('Tp (deg C)')
xlabel ('Y (m)')
See Pass Extra Parameters to ODE Function for a thorough explanation.

Steven Lord
Steven Lord 2016-9-17
See the example "Pass Extra Parameters to ODE Function" on the documentation page for ode45.

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by