MATLAB: Problem with returning to Main function from subfunction

event location propertyfunctionodeodesetordinary differential equation return

Hi everybody,
I'm running into a problem when I want to execute a code that is schematic like the following (See below). It is supposed to produce the orbital decay of space objects. I use a ODE integrator like Runge-Kutte Fehleberg to get the rates of change. When a certain value is reached (like altitude is 0) I want to abort the integration and return the values to the main function for plotting etc. The integration and orbit decay seems to work ok but when the abort criteria is reached I get the following error:
——————————————————————-
_Error in SimpleDecay>rates (line 135) dfdt = zeros(7,1);
Output argument "dydt" (and maybe others) not assigned during call to "C:\Users\…\SimpleDecay.m>SimpleDecay/rates".
Error in rkf45 (line 79) f(:,i) = feval(ode_function, t_inner, y_inner);
Error in SimpleDecay (line 86) [t,f] = rkf45(@rates, tspan, f0);
_————————————————————–
I'm not sure whether I placed the abort 'if' correctly or what the problem really is so every help is highly appreciated!
Thanks in advance, David
The code is schematic like this:
function main
%Some definitions etc.
%Define timespan of integration & initial value vector
% Calling the integrator
[t,f] = rkf45(@rates, tspan, f0);
%return the solutions
a = f(:,1);
%etc.

plotting %as a subfunction call
return
function dydt = rates(ti,y)
dfdt = zeros(7,1);
initial vector definition
a = y(1);
%etc.
% Define some needed values
% Return when value is reached
if a < Re
return
end
%Calculate rates
dadt = ...
% etc.
% Load derivatives into output vector
dydt(1) = dadt;
end % end rates
end % end main

Best Answer

You must assign values to any output variable used by the calling function if you are going to use "return" (explicitly or implicitly). This is basic MATLAB, not dependent on the fact that you are using an ode solver.
Early stopping for the MathWorks-provided ode* solvers is handled by passing an options structure (usually created with odeset) that includes an Events option that provides a function handle to test for a stop.
Examining the code for the rkf45 contribution, I see that it has no provision for early stopping except for this: returning a very large value from the user function will cause early termination. The easiest way to get the necessary large value would be to return infinity.