MATLAB Answers

How can i use dsolve and symbolic expressions in for loop?

4 views (last 30 days)
Hi,
In my code, i have to change initial conditions for each step to solve the diff. eqs., so i use for loop.
To solve the eqs, i select dsolve command but at the solutions, i still see my state variables.
And, code doesn't apply initial conditions of x2.
I cannot fix the problem.
Is there a practial way to make it?
Thx!
clear all
clc
u_input=[5 6 7];
x1_inl=[10 11 21];
x2_inl=[10 56 1];
for p1=1:1:3;
syms x1 x2 u
alfa_f(p1)=u-(40*x1/4)-(x1/18);
alfa_r(p1)=(30*x1/5)-(x1/9);
Prl(p1)=atand(alfa_r(p1));
Prr(p1)=atand(alfa_r(p1));
Pfl(p1)=atand(alfa_f(p1));
Pfr(p1)=atand(alfa_f(p1));
x1_dot(p1)=Prl(p1)/1500+Prr(p1)/1500+Pfr(p1)/1500+Pfl(p1)/1500-40*x1;
x2_dot(p1)=((Pfl(p1)+Pfr(p1))*10/1800)+((Prl(p1)+Prr(p1))*15/1500);
x1_dot(p1)=subs(x1_dot(p1),{x1 x2 u},{x1 x2 u_input(p1)});
x2_dot(p1)=subs(x1_dot(p1),{x1 x2 u},{x1 x2 u_input(p1)});
syms x1(t) x2(t) u
ode1(p1)=diff(x1,t)==x1_dot(p1);
ode2(p1)=diff(x2,t)==x2_dot(p1);
odes{:,p1}=sym2cell([ode1(p1); ode2(p1)]);
cond1(p1)=x1(0)==x1_inl(p1);
cond2(p1)=x2(0)==x2_inl(p1);
conds{:,p1}=sym2cell([cond1(p1); cond2(p1)]);
x0{p1}=dsolve(cell2sym(odes{:,p1}),cell2sym(conds{:,p1}));
x0{:,p1}=(struct2cell(x0{p1}));
xx0(p1,:)=[x0{1,p1}{1,1}, x0{1,p1}{2,1}] %Solutions for 3 different initial cond.s
end

Accepted Answer

Walter Roberson
Walter Roberson on 6 Nov 2020
Edited: Walter Roberson on 9 Nov 2020
syms x1 x2 u
[...]
syms x1(t) x2(t) u
You are redefining x1 and x2. When you do that, MATLAB will not update previous references to x1 and x2.
The situation is very similar to as if you had done
a = 1;
b = a * 10;
a = 2;
When you do the assignment to b, the current value of a at the time of statement execution is copied and used to calculate b, and then b forgets all about how it was defined. The a = 2 after that does not suddenly have b evaluate to 20 .
Just so when you use syms x1 and calculate with x1 then all those expressions copy the x1 that is not a function. Then you replace x1 with something else, and when you do that, the expressions that used the non-function x1 do not suddenly get changed to use the function x1.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by