MATLAB: How to pass out extra parameters using ODE23 or ODE45 from the MATLAB ODE suite

additionalextraMATLABodeoutoutputparameterpassvariable

I would like to return some parameters from the ode45 solution that do not need to be integrated, but which are important to the result. I would like to have the function I pass to ODE23/ODE45 return extra parameters which the ODE solver ignores during the computation but stores for later review.

Best Answer

There is no method for passing out additional parameters from the ODE function using the ODE solvers provided in the MATLAB ODE suite (e.g., ODE45). These additional parameters, however, can be passed out after ODE45 returns a solution.
For example, consider the ODE:
y' = x + k*y
where
k = x^2 + y^2
If you have a need to obtain "k" for specified "x" and "y", you can create the following ODE function:
function [dydx k] = myode(x, y)
k = x.^2 + y.^2;
dydx = x + k.*y;
The solution to the ODE can be solved using the commands:
[X Y] = ode45(@myode, [0 5], 1);
Then, "k" can be obtained via the command:
[dydx k] = myode(X, Y);
If you would like to obtain a series of values that are computed during the solution algorithm, you can declare a variable as PERSISTENT, and append the value computed during each call to the ODE function to the end of this persistent variable.
For example, consider the previous ODE. If you would like to obtain a vector of the "x" and "y" values specified for each call to the ODE function, try the following ODE function:
function [dydx xvt yvt] = myode(x, y)
persistent xv yv
xv = [xv; x];
yv = [yv; y];
k = x.^2 + y.^2;
dydx = x + k.*y;
if nargout>1
xvt = xv; yvt = yv;
end
The solution to the ODE can be solved using the commands:
[X Y] = ode45(@myode, [0 5], 1);
Then, "xv" and "yv" can be obtained via the command:
[dydx xv yv] = myode([], []);
You could also use the ASSIGNIN, EVALIN, or SAVE functions. The ASSIGNIN function allows you to assign variables into workspace, and the EVALIN function evaluates an expression in the workspace. The SAVE function saves workspace variables to disk. The following example demonstrates how to assign the variable 'dy' from the ODEFUN to the workspace. Save the following into a function file named "odefun.m":
function dy =odefun(t,y)
dy=1;
varToPassOut=2;
assignin('base','varInBase',varToPassOut);
evalin('base','varPassedOut(end+1)=varInBase');
After writing this function, execute the following at the MATLAB command prompt:
varPassedOut=0
[T,Y] = ode45(@odefun,[0 12],[0]);
varPassedOut=varPassedOut(2:end);
Note that you need to define the variable "varPassedOut" in the base workspace before calling ODE45, or you will receive an error.
Related Question