MATLAB Answers


Can you use ODE45 in a for loop?

Asked by Martin
on 4 Feb 2013

Hi there, I am having to solve a pair of coupled 1st ODEs. I also need to change the integration time like this:

ti = 0
tf = 10
timestep = 0.1
num    = (tf-ti)/timestep;
timerange = linspace(ts,tf,num);
for i = 1:length(timespan)
        tt = timerange(i); %defining the integration time start.
        [t,x]=ode45('func',[tt:0.01:tf],[0,0]);  %solving the coupled odes.

So what is happening is that I am changing the start integration in the [T0 TFINAL] vector. Is there a way that I can save all of the t's and the x's as a matrix/for each iteration so that I can plot all of the solutions to the coupled odes?



Log in to comment.

1 Answer

Answer by Matt Tearle
on 4 Feb 2013
Edited by Matt Tearle
on 4 Feb 2013
 Accepted Answer

Given that ode45 is a variable step solver, you don't know how many t and x values you'll get each time, so the simplest solution would be to save them all in cell arrays:

n = length(timerange);
allx = cell(n,1);
allt = cell(n,1);
for i = 1:n
   allx{i} = x;
   allt{i} = t;

But if all you're trying to do is plot them all, why not just plot each one as you go? Use a hold on or hold all and then plot(t,x) in the loop.

(Also, [t,x] = ode45(@func,[tt... -- function handles are cooler than strings :) )


Basically I press run on the program and it immediately brings the error message up, so I am unsure what it is doing. This is the full error message I get.

 SWITCH expression must be a scalar or string constant.
Error in odeevents (line 32)
    switch lower(eventFcn)
Error in ode45 (line 148)
[haveEventFcn,eventFcn,eventArgs,valt,teout,yeout,ieout] = ...
Error in ode45testfunc2 (line 39)
          [t,x]=ode45('cwfield',tt:0.01:tf,[0,0],opts);  %solving the coupled odes.

Maybe the problem is is that some solutions never pass through zero? other than that I was thinking of having to do it the old way I was but using the cellfun function.

I'm guessing you're using the code I provided to define the event (using a function handle in odeset). If so, the problem might be that you're using a string to define the ODE rate equations and a function handle to define the event function. Try changing your call to ode45 to


(BTW, not going through 0 isn't a problem -- it just means the event won't ever be triggered, so ode45 will integrate until tf).

Yea I thought that it was because of using strings rather than handles...but when I use the @cwfield I get a different error! I have managed to get around this in the end using a bit of brute force, but I'll return to this when I have some time on Monday.

Thanks for all of the help, I am getting some really nice results from the code now.

Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Win prizes and improve your MATLAB skills

Play today