how can i convert a string that is "A*x+B*y" to an mathematical differential expression that will be computed later on using ode solver, currently the error is

2 ビュー (過去 30 日間)
function dydt = odefcn(t,y,A,B)
dydt = zeros(2,1);
dydt(1) = y(2);
dydt(2) = evalin(symengine,'A*y(1)-B*y(2)');
The following error occurred converting from sym to double:
DOUBLE cannot convert the input expression into a double array.
Error in odefcn (line 5)
dydt(2) = evalin(symengine,'(A/B)*y(1)-B*y(2)');
Error in @(t,y)odefcn(t,y,A,B)
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options,
varargin);

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 1 月 28 日
function dydt = odefcn(t,y,A,B)
dydt = zeros(2,1);
dydt(1) = y(2);
dydt(2) = A*y(1)-B*y(2);
Do not use the symbolic engine for this.
If you must use the symbolic engine specifically, then
function dydt = odefcn(t,y,A,B)
dydt = zeros(2,1);
dydt(1) = y(2);
part1 = feval(symengine, '_mult', A, y(1));
part2 = feval(symengine, '_mult', B, y(2));
d2 = feval(symengine, '_minus', part1, part2);
dydt(2) = double(d2);
There is no reason to do this for such a simple expression, so the only reason to show this is for illustration about how you could call into the symbolic engine if you really needed to, such as if you needed to access a MuPAD routine that is not available through MATLAB.
You should avoid calling the symbolic engine inside an ode function, as executing in the symbolic engine is slower than executing numerically.
  2 件のコメント
Abhijot Mann
Abhijot Mann 2017 年 1 月 29 日
Thanks a lot but it has not clarified one very basic point as to how can i convert "Ax+By" which is a string to an expression like Ax+By in matlab. Is there a way out
Walter Roberson
Walter Roberson 2017 年 1 月 29 日
In current versions you can sym() the string to get a symbolic expression that can be used by the symbolic ode functions. You can subs() on it to pull in the current values of A and B. You can matlabFunction to create a function handle that can be used with the numeric ode routines. However if your purpose is to use the numeric ode routines then skip the symbolic toolbox entirely and use str2func.

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

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by