How to pass a function handle of an anonymous function into ode45 function in matlab?

66 ビュー (過去 30 日間)
Amr  Tolba
Amr Tolba 2014 年 6 月 9 日
編集済み: Cedric 2014 年 6 月 10 日
I need to pass an inline anonymous function into ode45 function in matlab but i have not managed to to that. I have looked through the help of matlab but didn't help me. let's give a code example to clarify:
I have a matrix function as follows: f_xyz = @(x,y,z) [-1 1 0;2 -1 -x;0 y -3]*[x;y;z];
and i would like to pass it into ode45 function with such syntax:
[T Y] = ode45(ode_function,time_interval,initial_values);
I checked many forums to get some hints but i didnt work please advise me how to do that?
P.S. :I know how to do that if we have a m-file function but i need it to be as an anonymous function.

回答 (1 件)

Cedric
Cedric 2014 年 6 月 9 日
編集済み: Cedric 2014 年 6 月 10 日
Assuming that your problem has 3 dimensions, so you have for example
x0 = [10; 5; 7] ; % [x1(0), x2(0), x3(0)], or
% [x(0), y(0), z(0)] with your notation.
where 10 is the initial condition for dim 1, etc, ODE45 will call the function f that it receives as 1st arg, referenced by its handle @f, with the following parameters:
f( t, x, ... )
where ... symbolize extra parameters that can be defined as extra parameters in the call to ODE45, or through an appropriate definition of the function/handle that you pass as 1st argument. You have therefore to pass a function which takes t and x in this order. If you have the freedom to define f_xyz, you should then define it as follows
f_xyz = @(t, x) [-1 1 0;2 -1 -x(1);0 x(2) -3] * x ;
If you cannot modify f_xyz, you can pass a handle on an intermediary anonymous function which plays the role of interface, adjusting parameters orders/structure:
% f_xyz defined elsewhere, you cannot access/modify it.
f_xyz = @(x,y,z) [-1 1 0;2 -1 -x;0 y -3]*[x;y;z];
% Call to ODE45 using an "interface" anonymous function.
[t, x_t] = ode45( @(t, x) f_xyz(x(1), x(2), x(3)), ... ) ;
Note that you can give a name to this interface function if you prefer not to deal with anonymous functions (but you'll often see people using anonymous functions here)..
interf = @(t, x) f_xyz(x(1), x(2), x(3)) ;
[t, x_t] = ode45( interf, ... ) ;
Hope it helps

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by