MATLAB: How to avoid creating a function file for the differential equations when solving ODE functions in MATLAB

@annonymouscompilecompilerdifferentialequationsfunctioninline()mathMATLABodeode15ode45

I am trying to let the users of my application specify their own differential equations and solve them using the ODE45 function without creating a function file.

Best Answer

For example, if you have a system of ODEs as follows:
y1' = y2*y3
y2' = -y1*y3
y3' = -0.51*y1*y2
You can avoid creating another function file for ODE functions by using an anonymous function if you are using MATLAB 7.0 (R14) or later:
You can set up the ODEs using an anonymous function in combination with the EVAL command:
str = '[y(2)*y(3);-y(1)*y(3);-0.51*y(1)*y(2)]';
f = eval(['@(t,y)',str]);
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
[T,Y] = ode45(f,[0 12],[0 1 1]',options);
If you are using previous versions, you can use the INLINE function:
Set up the ODEs using the INLINE function:
f = inline('[y(2)*y(3);-y(1)*y(3);-0.51*y(1)*y(2)]','t','y')
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
[T,Y] = ode45(f,[0 12],[0 1 1]',options);