Convert syms struct to numerical values

4 views (last 30 days)
JC.UT
JC.UT on 21 Sep 2021
Answered: sai charan sampara on 25 Apr 2024
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]

Answers (1)

sai charan sampara
sai charan sampara on 25 Apr 2024
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');

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!