How can I use equations from a matrix, using symbolic variables, inside the function file for ode45 ?

4 Ansichten (letzte 30 Tage)
I want to use time dependent equations directly from a matrix (i.e. product of matrices) in the function file. keeping it simple using 2*2 matrices.
%function file
function dbdt =timedb(t,b)
global w0 l1 d gc gm1 phi
dbdt=zeros(4,1);
g=l1^2/d;
a=[-g*sin(phi) w0-g*cos(phi);-w0-g*cos(phi) g*sin(phi)-gm1];
syms b11 b12 b21 b22
b=[b11 b12; b21 b22];
syms t
% dbrdt=diff(b)./diff(t);
dbrdt=a*b+b*a.';
%if I write
%dbdt=a*b+b*a.';%error is: TIMEDV must return a column vector.
%I want to use compcat form smthing like this
dbdt(1) = dbrdt(1,1);
dbdt(2)=dbrdt(1,2);
dbdt(3)=dbrdt(2,1);
dbdt(4)=dbrdt(2,2);
Manually it can be done like this which works well.
% dbdt(1) = 2*A(1,1)*b(1)+A(1,2)*b(2)+b(3)*A(1,2);
% dbdt(2)=A(1,1)*b(2)+A(1,2)*b(4)+b(1)*A(2,1)+b(2)*A(2,2);
% dbdt(3)=A(2,1)*b(1)+A(2,2)*b(3)+b(3)*A(1,1)+b(4)*A(1,2);
% dbdt(4)=A(2,1)*b(2)+2*A(2,2)*b(4)+b(3)*A(2,1);
% with initial conditions
% b1_0=1;
% b2_0=0;
% b3_0=0;
% b4_0=0;
but I want to use compact from of equtions, using the syms, as in the previosu part.
My main file looks like this
b11_0=1;
b12_0=0;
b21_0=0;
b22_0=0;
bb=[b11_0, b12_0, b21_0 b22_0];
[T,B]=ode45('timedb',tspan,bb);
it gives error:
Unable to perform assignment because value of type 'sym' is not convertible to 'double'. How can I solve this issue?
  6 Kommentare
Torsten
Torsten am 28 Jan. 2022
Maybe the reshape command gives the transposed matrix of B.
Then use reshape(...).'
Anil Kumar
Anil Kumar am 28 Jan. 2022
Dear Torsten, Thanks!. Wroking perfect. there was a typo, removing that unnecessary comment.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Steven Lord
Steven Lord am 26 Jan. 2022
It is possible to perform calculations using symbolic variables inside the function file whose handle you pass into ode45 as the first argument. However whether or not you perform the calculations symbolically inside your function file, your function file must return a double column vector.
Looking specifically at what you've written, these lines are problematic.
syms b11 b12 b21 b22
b=[b11 b12; b21 b22];
syms t
ode45 will call your function with inputs and inside your function those inputs are known as t and b. These lines I've quoted overwrite those inputs with symbolic variables, so you're completely ignoring what ode45 asked you to compute.

Kategorien

Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by