From inline to anonymous function

Hello, I've been struggling in trying to migrate the following inline function (which serves as an input to ode45), to an anonymous function. The function is the following:
g = inline(sprintf('[%s; %s]', dx1dt, dx2dt), 't', 'x');
which I merelely converted to:
g = @(t,x) sprintf('[%s; %s]', dx1dt, dx2dt);
I tried a couple of combinations but it seems like, after the @(t,x), the sprintf part does not get evaluated. I think I'm missing something, how I should I solve this?
Edit: Some clarification about the context.
The dx1dt and dx2dt are symbolic functions, and using the inline function the output is the following:
>> g
%Inline function:
% g(t,x) = [x(2); -(2943*cos(x(1)))/200]

回答 (3 件)

Star Strider
Star Strider 2015 年 5 月 13 日
編集済み: Star Strider 2015 年 5 月 13 日

0 投票

Completely guessing here (because the ‘dx1dt’ and ‘dx2dt’ aren’t shown).
See if this works:
g = @(t,x) [dx1dt(t,x), dx2dt(t,x)];
You may need to experiment with that, perhaps:
g = @(t,x) [dx1dt(t,x); dx2dt(t,x)];
instead, depending on what your functions are and what size vectors they return.
EDIT —
Your ODE function then becomes:
g = @(t,x) [x(2); -(2943*cos(x(1)))/200];
That should work in ode45 (or whatever solver you are using) without further modification.
Walter Roberson
Walter Roberson 2015 年 5 月 13 日

0 投票

g = matlabFunction([dx1dt, dx2dt], [t,x]);
Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2015 年 5 月 13 日
編集済み: Alfonso Nieto-Castanon 2015 年 5 月 13 日

0 投票

if you have the symbolic toolbox:
g = matlabFunction(sprintf('[%s; %s]', dx1dt, dx2dt));
otherwise your best bet is probably something like:
g = eval(sprintf('@(%s)[%s;%s]',strjoin(symvar(dx1dt),','),dx1dt,dx2dt));
or perhaps simply:
g = eval(sprintf('@(t,x)[%s;%s]',dx1dt,dx2dt));

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

質問済み:

2015 年 5 月 13 日

編集済み:

2015 年 5 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by