How can I convert set of symbolic functions into function handle so that they can be used as input to ode45?

For example, I have to solve the following equations
if true
syms x(t) y(t) z(t)
eq1 = diff(x,t) == -x+3z;
eq2 = diff(y,t) == -y+2z;
eq3 = diff(z,t) == x^2-2z;
end
I can use ode45.
if true
f = @(t,x) [-x(1)+3*x(3);-x(2)+2*x(3);x(1)^2-2*x(3)];
[t,xa] = ode45(f,[0 1.5],[0 1/2 3]);
end
Is there any way I can generate the following line automatically from the equations I get(they are symbolic).
f = @(t,x) [-x(1)+3*x(3);-x(2)+2*x(3);x(1)^2-2*x(3)];
In my case, the equation is generated inside the code, so I don't know the coefficients beforehand to write that line.

2 commentaires

You could convert the symbolic expression into a MATLAB function as madhan ravi suggested, but have you tried the functionality included in Symbolic Math Toolbox to solve systems of differential equations directly?
I tried that, but there is no analytical solution to the equations I am trying to solve. So I will not be able to use the standard functionalities.

Connectez-vous pour commenter.

 Réponse acceptée

EDITED
syms x(t) y(t) z(t)
eq1 = diff(x,t) == -x+3*z;
eq2 = diff(y,t) == -y+2*z;
eq3 = diff(z,t) == x^2-2*z;
vars = [x(t); y(t); z(t)]
V = odeToVectorField([eq1,eq2,eq3])
M = matlabFunction(V,'vars', {'t','Y'})
interval = [0 1.5]; %time interval
y0 = [0 1/2 3]; %initial conditions
ySol = ode45(M,interval,y0);
tValues = linspace(interval(1),interval(2),1000);
yValues = deval(ySol,tValues,1); %number 1 denotes first solution likewise you can mention 2 & 3 for the next two solutions
plot(tValues,yValues)

5 commentaires

I tried using matlabFunction, but it was giving me warnings saying that in the above equations x, y and z are not valid matlab functions. When the equation has the terms x(t), y(t) and z(t), it is implicitly assuming that x, y, and z are functions.
If matlabFunction worked for you, can you put up some sample code to solve the above equations using ode45 if the initial equations are symbolic.
if true
syms x(t) y(t) z(t)
end
After solving my problem I got the expressions
if true
eq1 = diff(x,t) == -x+3z;
eq2 = diff(y,t) == -y+2z;
eq3 = diff(z,t) == x^2-2z;
end
The initial conditions are x(0) = 0, y(0) = 1/2, z(0) = 3 and the variable t belongs to [0,1.5].
I thought of using ode45 to solve the differential equations. For that purpose, I need to convert my symbolic equations into function handle.
Thank you very much, Sir. I was stuck at this point for the last 2.5 hours.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by