4

Let's suppose that we have the following solver for a system of first-order ODEs:

   % func.m
   function dydt = func(t,y)
   dydt = [y(2); (1-y(1)^2)*y(2)-y(1)];

and the main code:

% solver.m
tspan=0:1:10;
[t,y] = ode45(@func,tspan,[2; 0]);

How to display in real-time the results, y1(t) and y2(t), for each time step t that the ode45 makes (t=0,1,2,...,10), without waiting for the whole code to finish?

Andreas K.
  • 9,282
  • 3
  • 40
  • 45

1 Answers1

5

The OutputFcn ode solver option should be used. For example, to plot the solution vs time, the built-in output function odeplot can be used:

options= odeset('OutputFcn',@odeplot);
[t,y] = ode45(@func,[0 200],[2; 0],options);

You can use your own output function. Here is an example:

myOutputFcn= @(t,y,flag)fprintf('t= %s y=  %s\n',mat2str(t),mat2str(y))*0;
options= odeset('OutputFcn',myOutputFcn);
[t,y] = ode45(@f,0:1:10,[2; 0],options);
AVK
  • 2,130
  • 3
  • 15
  • 25
  • I changed the code to this: tspan=0:1:10; [t,y] = ode45(@func,tspan,[2; 0],options); How to print t and y1(t), y2(t), for t=0,1,2,...,10? Your code gives some strange results for t and y. Here y has two columns. – Andreas K. Oct 20 '16 at 12:57
  • @Andyk Sorry, there was some bugs when using `fprintf`. I have corrected the answer – AVK Oct 20 '16 at 13:30
  • Why did you multiply the fprintf by 0? – Andreas K. Oct 20 '16 at 13:33
  • The output function should return `0` to continue and `1` to stop; `fprintf` returns the number of bytes writen (not equal to `0`). The simpliest way to return zero in our case (from an anonymous function) is just to multiply this number by `0` – AVK Oct 20 '16 at 13:38