Why Dsolve considers my equations' variables constants!?

clear all
Nx = 2; % number of state equations
Nu = 1; % number of control parameters
% x = sym('x%d', [1 Nx]);
% p = sym('p%d', [1 Nx]);
syms u t
syms x p [1 Nx]
% State equations
Dx(1) = x(2);
Dx(2) = -x(2) + u(1);
% Cost function inside the integral
g = 0.5*u(1)^2;
% Hamiltonian
H = g;
for i = 1 : Nx
H = H + p(i)*Dx(i);
end
% Costate equations
for i = 1 : Nx
Dp(i) = -diff(H,x(i));
end
% solve for control u
du = diff(H,u);
sol_u = solve(du,u);
% Substitute u to state equations
for i = 1 : Nx
Dx(i) = subs(Dx(i),u,sol_u);
end
% convert symbolic objects to strings for using 'dsolve'
% need ti automate this solving
clear x p
syms x(t) p(t) [1 Nx]
eqx = diff(x,t)==Dx
eqx(t) = 
eqp = diff(p,t)==Dp
eqp(t) = 
eq = [eqx,eqp];
sol_h = dsolve(eqx,eqp);

1 Kommentar

these are the final diff. equations:
eq = [diff(x1(t), t) == x2, diff(x2(t), t) == - p2 - x2, diff(p1(t), t) == 0, diff(p2(t), t) == p2 - p1]
the solution of dsolve is:
sol_h =
struct with fields:
x2: C2 - t*(p2 + x2)
x1: C1 + t*x2
p1: C3
p2: C4 - t*(p1 - p2)
But the answer should be like:
x2: (C3*exp(t))/2 - C4 + (C2*exp(-t))/2
x1: (C3*exp(t))/2 - C4*t - C1 - (C2*exp(-t))/2
p1: C4
p2: C4 - C3*exp(t)
I got the first solution by dsolve(eq) in my script, the second solution i got by dsolve(diff(x1(t), t) == x2, diff(x2(t), t) == - p2 - x2, diff(p1(t), t) == 0, diff(p2(t), t) == p2 - p1) in the workspace
Where is the ptoblem?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

syms t x1(t) x2(t) p1(t) p2(t)
eq = [diff(x1, t) == x2, diff(x2, t) == - p2 - x2, diff(p1, t) == 0, diff(p2, t) == p2 - p1]
eq(t) = 
dsolve(eq)
ans = struct with fields:
x2: (C3*exp(t))/2 - C4 + (C2*exp(-t))/2 x1: (C3*exp(t))/2 - C4*t - C1 - (C2*exp(-t))/2 p1: C4 p2: C4 - C3*exp(t)

3 Kommentare

Thank you Torsten, but my code goal is to not write index number manully x1 x2 p1 p2, so i used syms x(t) p(t) [1 Nx], and by defining Nx, the code generats the approprate number of parameters, but here the code did not responded as expected!
Torsten
Torsten am 11 Feb. 2024
Bearbeitet: Walter Roberson am 11 Feb. 2024
You cannot create arrays of symbolic functions in MATLAB, and this would be necessary if you wanted to proceed as you try in your code:
Thank you, this was helpful

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by