Hi I just came across the same problem. I run a simulation with different parameters and for some parameters it takes very long time. Sometimes it's just a numerical instability.
To stop the function by a timeout I use events . This example will stop the calculation after 5 seconds and you will get what the solver could calculate during this time.
function Results = RunCalculation(Parameters)
% 1. define a link to an an event function which will stop calculation
xoverFcn = @(T, Y) MyEventFunction(T, Y);
% 2. register this function as an event function
options = odeset('Events',xoverFcn);
% 3. start a stopwatch timer, if you already use one, define a new one:
% tic(ticID)
% then ticID should be unique for each run and global for this function.
tic;
% Run the model
[T,Y] = ode45(NPZModel, TSpan, [1, 1, 1], options);
%%Define the event function
function [VALUE, ISTERMINAL, DIRECTION] = MyEventFunction(T, Y)
%The event function stops when VALUE == 0 and
%ISTERMINAL==1
%a. Define the timeout in seconds
TimeOut = 5;
%
%b. The solver runs until this VALUE is negative (does not change the sign)
VALUE = toc-TimeOut
%c. The function should terminate the execution, so
ISTERMINAL = 1;
%d. The direction does not matter
DIRECTION = 0;