Convert syms struct to numerical values

5 ビュー (過去 30 日間)
JC.UT
JC.UT 2021 年 9 月 21 日
回答済み: sai charan sampara 2024 年 4 月 25 日
I need to add in initial condition (x,y)=(1,1). The solution, S will yield struct with fields. I'm trying to convert them to numerical values in order to plot directional fields. How do I use subs or double to convert them , I'm having a difficult time using documentation to solve this one.
syms x(t) y(t)
ode1=diff(x)==2*x+y;
ode2=diff(y)==x+y;
cond=;
odes=[ode1 ode2 cond];
S=dsolve(odes)
S =
struct with fields:
y: [1×1 sym]
x: [1×1 sym]
  1 件のコメント
KSSV
KSSV 2021 年 9 月 21 日
Read about subs and double.

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

回答 (1 件)

sai charan sampara
sai charan sampara 2024 年 4 月 25 日
Hello,
To solve the ode with initial condition as (x,y)=(1,1). You can do the following:
syms x(t) y(t)
ode1=diff(x)==2*x+y;
ode2=diff(y)==x+y;
cond1=x(0)==1;
cond2=y(0)==1;
odes=[ode1 ode2 cond1 cond2];
S=dsolve(odes)
S = struct with fields:
y: exp((t*(5^(1/2) + 3))/2)*(5^(1/2)/10 + 1/2) + (5^(1/2)*exp(-(t*(5^(1/2) - 3))/2)*(5^(1/2) - 1))/10 x: exp((t*(5^(1/2) + 3))/2)*(5^(1/2)/2 + 1/2)*(5^(1/2)/10 + 1/2) - (5^(1/2)*exp(-(t*(5^(1/2) - 3))/2)*(5^(1/2)/2 - 1/2)*(5^(1/2) - 1))/10
double(subs(S.x,t,0))
ans = 1
double(subs(S.y,t,0))
ans = 1
As shown above you can use "subs" to substitute the value of symbolic variable "t" with the required value in the solutions for both "x" and "y". Then "double" can be used to simplify the value from symbolic expression to "double" data type. In the same way "subs" and "double" can be used to get the value of "x" and "y" for any time value. In the above case as required the initial values of "x" and "y" are 1.
To get the directional fields you can use the following code:
[x, y] = meshgrid(0:0.5:2, 0:0.5:2);
dx_dt=@(x,y) 2*x+y;
dy_dt=@(x,y) x+y;
dx=dx_dt(x,y);
dy=dy_dt(x,y);
quiver(x, y, dx, dy);
xlabel('x');
ylabel('y');

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by