title: Matlab - sometimes ode45 takes long time to return
body: <p>Here is the code</p>
  <pre><code>global a b c
  a=35
  b=3
  c=28
  
  for R = a-3 : a+3
      for N = b-2 : b+2
          for L = c-2 : c+2
              a=R;
              b=N;
              c=L;
              ode_interupt_demo
              plot3(x(:,3), x(:,2), x(:,1));
              S= [R N L]
              pause(1)
              close
          end
      end
  end
  
  function dxdt=fun1(t,x)
  global a b c
   
  dxdt(1)=a*(x(2)-x(1));
  dxdt(2)=(c-a)*x(1)-x(1)*x(3)+c*x(2);
  dxdt(3)=x(1)*x(2)-b*x(3);
  dxdt=dxdt';
  end
  
  function status = interuptFun(t,y,flag,interupt_time)   %#ok&lt;INUSL&gt;
  persistent INIT_TIME;
  status = 0;
  switch(flag)
      case 'init'
          INIT_TIME = tic;
      case 'done'
          clear INIT_TIME;
      otherwise
          elapsed_time = toc(INIT_TIME);
          if elapsed_time &gt; interupt_time
              clear INIT_TIME;
              str = sprintf('%.6f',elapsed_time);
              error('interuptFun:Interupt',...
                   ['Interupted integration. Elapsed time is ' str ' seconds.']);
          end
  end
  
  
  function ode_interupt_demo
  
  tspan = [0 10]; y0 = [0.5 1 1];
  interupt_time = 10;
  outputFun= @(t,y,flag)interuptFun(t,y,flag,interupt_time);
  opts = odeset('AbsTol',1e-8,'RelTol',1e-5,'OutputFcn',outputFun);
  
  try
      [t,x] = ode45(@fun1,tspan,y0,opts);
      
  catch ME
      if strcmp(ME.identifier,'interuptFun:Interupt')
          disp(ME.message);
          % Do other things
      else
          rethrow(ME); % It's possible the error was due to something else
      end
  end
  </code></pre>
  <p>In Matlab I am solving a differential equation, but sometimes it takes <code>ode45</code> a long time to return. I have used code that was suggested in <a href="https://stackoverflow.com/a/25583703/2278029">this post</a> to solve my similar problem, but it will not return a value from <code>ode45</code>. Instead I get</p>
  <blockquote>
  <p>??? Undefined variable x.</p>
  <p>Error in ==&gt; goo at 13<br>
  plot3(x(:,3), x(:,2), x(:,1));</p>
  </blockquote>