How to use matlabFunction to create a proper function for ode45?
2 views (last 30 days)
Show older comments
I have used Matlab's symbolic toolbox to derive a set of equations for a system of ODEs. This required me to set all of my variables as being dependent on time (e.g. syms x1(t)) because I needed to take time derivatives during the derivation.
Now, if I run matlabFunction() on the resulting expressing, it outputs a function handle that depends only on t, but what I need is a function handle that depends on (t, [x1(t);....;xn(t)]) for use in ode45. How do I obtain this function handle dynamically?
0 Comments
Answers (1)
Star Strider
on 2 Apr 2017
This is actually more straightforward than it looks. You first have to call odeToVectorField to create the essential function construction and then use matlabFunction to create it as a function.
In the matlabFunction call, use the 'Vars' argument to return the variables-of-interest in the order you want them. (Normally, ‘t’ would not be included, but you can request it with 'Vars'.) This code also contains a tweak that retrieves the substituted variables from the odeToVectorField call and displays them in the legend of the integrated function.
Example —
syms t w y(t) Y
Dy = diff(y,t);
D2y = diff(y,t,2);
Eqn = D2y + 0.2*Dy - y - y^3 == 0.3*cos(w*t);
[DEs,DEsbs] = odeToVectorField(Eqn); % Request Substituted Variables
DEfcn = matlabFunction(DEs, 'Vars',[t,Y,w]) % Use 'Vars' To Put Arguments In The Correct Order
w = 10;
tspan = linspace(0,5,250);
ic = [0; 0];
[tv,ys] = ode45(@(t,yv) DEfcn(t,yv,w), tspan, ic);
figure(1)
plot(tv, ys)
grid
lgndc = sym2cell(DEsbs); % Get Substituted Variables
lgnds = regexp(sprintf('%s\n', lgndc{:}), '\n','split'); % Create Cell Array
legend(lgnds(1:end-1), 'Location','NW') % Display Legend
That should do what you want.
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox 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!