dsolve using a string

1 回表示 (過去 30 日間)
Matt Baron
Matt Baron 2021 年 4 月 2 日
回答済み: Amal Raj 2024 年 2 月 22 日
Team,
I am trying to figure out why the code below won't work. This is taken out of a larger program where it asks at the beginning using input "What equation would you like solved?" That is why dfeq = '2*x*y' at this particular point.
>> initcondx=1
initcondx =
1
>> initcondy=1
initcondy =
1
>> dfeq='2*x*y'
dfeq =
'2*x*y'
>> syms y x y(x)
>> ode=diff(y,x)==str2sym(dfeq)
ode(x) =
diff(y(x), x) == 2*x*y
>> cond=y(initcondx)==initcondy
cond =
y(1) == 1
>> dsolve(ode,cond)
Error using mupadengine/feval (line 187)
Expecting an ODE in the specified variable.
Error in dsolve>mupadDsolve (line 340)
T = feval(symengine,'symobj::dsolve',sys,x,options);
Error in dsolve (line 194)
sol = mupadDsolve(args, options);
  2 件のコメント
Matt Baron
Matt Baron 2021 年 4 月 3 日
I've got the problem narrowed down to this/
If I input an equation into the variable dfeq using input
dfeq then equals '2*x*y'
If I then use str2sym(dfeq), it outputs 2*x*y
however when I use that with diff(y,x)==str2ym(dfeq), it comes out without the y(x)
See below;
>> ode=diff(y,x)==str2sym(dfeq)
ode(x) =
diff(y(x), x) == 2*x*y
>> ode=diff(y,x)==2*x*y
ode(x) =
diff(y(x), x) == 2*x*y(x)
How do I get it keep the y(x) with str2sym?
Matt Baron
Matt Baron 2021 年 4 月 9 日
I think I have figured out this is just not possible to do.

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

回答 (1 件)

Amal Raj
Amal Raj 2024 年 2 月 22 日
When using str2sym to convert a string to a symbolic expression, it treats the variables as independent symbols and does not associate them with any specific function. That's why when you use str2sym(dfeq) in the diff function, it does not include the (x) notation for the function y(x).
To keep the y(x) notation, you can explicitly define y as a function of x using the symfun function. Here's an example:
dfeq = '2*x*y';
syms y(x) x; % Define symbolic variables
y = symfun(y(x), x); % Define y as a function of x
ode = diff(y, x) == str2sym(dfeq); % Define the ODE
Now, when you use diff(y, x), it will include the (x) notation for the function y(x).

カテゴリ

Help Center および File ExchangeEquation Solving についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by