How can I use equations from a matrix, using symbolic variables, inside the function file for ode45 ?
Show older comments
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 Comments
Torsten
on 26 Jan 2022
By removing the syms lines in your function file and replacing
[T,B] = ode45(...
by
[T,B] = ode45(@(t,b)timedb(t,b(1),b(2),b(3),b(4)),tspan,bb)
and
function dbdt = ...
by
function dbdt(t,b11,b12,b21,b22)
and by defining the undefined variable geff somewhere.
Anil Kumar
on 26 Jan 2022
Torsten
on 26 Jan 2022
If you have more equations, use
[T,B] = ode45(@timedb,tspan,bb)
function dbdt = timedb(t,bvec)
and in the code
b = reshape(bvec,sqrt(numel(b)),sqrt(numel(b)))
Anil Kumar
on 28 Jan 2022
Edited: Anil Kumar
on 28 Jan 2022
Torsten
on 28 Jan 2022
Maybe the reshape command gives the transposed matrix of B.
Then use reshape(...).'
Anil Kumar
on 28 Jan 2022
Answers (1)
Steven Lord
on 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.
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!