Function handles and passing parameters to ode solver

20 ビュー (過去 30 日間)
Leon Stangenberg
Leon Stangenberg 2021 年 2 月 18 日
編集済み: Stephen23 2021 年 2 月 18 日
I'm trying to create a function that can be used in an ode solver but can't figure out how to properly pass parameters.
Currently the code is looking like this:
[t,L] = ode45(@f,[0 maxTime],ab);
The function uses the global variables defined in the file, but I'm trying to avoid using those global variables.
function dy = f(t,y)
global c_h c_v k_h k_v l_v l_h g m J_s h myTorque;
dy = zeros(4,1);
%zdotdot
dy(1) = y(2);
dy(2) = ...% Goes on using the variables from above
%thetadotdot
dy(3) = y(4);
dy(4) = ...% Goes on using the variables from above
end
I'd imagine the function looking more like:
function dy = f(t,y,c_h,c_v,k_h,k_v,l_v,l_h,g,m,J_s,h,myTorque)
dy = zeros(4,1);
%zdotdot
dy(1) = y(2);
dy(2) = ...% Goes on using the variables from above
%thetadotdot
dy(3) = y(4);
dy(4) = ...% Goes on using the variables from above
end
How would I call a function like this within the ode solver using the parameters as well?

採用された回答

Stephen23
Stephen23 2021 年 2 月 18 日
編集済み: Stephen23 2021 年 2 月 18 日
Like this:
c_h = ... some value;
c_v = ... some value;
... all the others variables
myTorque = ... some value;
% Now define an anonymous function with exactly two input arguments:
fun = @(t,y) f(t,y,c_h,c_v,k_h,k_v,l_v,l_h,g,m,J_s,h,myTorque);
% and provide that function handle to the ODE solver:
[t,L] = ode45(fun,[0 maxTime],ab);
  1 件のコメント
Leon Stangenberg
Leon Stangenberg 2021 年 2 月 18 日
編集済み: Leon Stangenberg 2021 年 2 月 18 日
Yes, thank you for that detailed answer, that was exactly what I couldn't figure out how to do.

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2021 年 2 月 18 日
The section of the documentation page for the ode45 function that talks about the odefun input argument links to a page that discusses a couple different techniques for passing additional parameters into the function you specify as the odefun input.
  1 件のコメント
Leon Stangenberg
Leon Stangenberg 2021 年 2 月 18 日
Thank you, that was what i was looking for, I don't know why I didn't come across that myself.

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

カテゴリ

Help Center および File ExchangeOrdinary Differential Equations についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by