Matlab real time plot

MATLAB

I'm new to matlab and I want to plot some data in real time.
My approach was follows:

figure;
hold on;

for i = 1:1000;
   plot(i, i);
   drawnow;
end

But it has poor performance.

I also found a suggestion here on stackoverflow: https://stackoverflow.com/q/3118918/1066838
but only the last set data are drawn, so I see always only one point on the figure.

Best Answer

Instead of doing a high-level plot call, consider adjusting the line handle properties, more specifically the XData and YData, in the loop:

figure(1);
lHandle = line(nan, nan); %# Generate a blank line and return the line handle

for i = 1:1000
    X = get(lHandle, 'XData');
    Y = get(lHandle, 'YData');

    X = [X i];
    Y = [Y i];

    set(lHandle, 'XData', X, 'YData', Y);
end

Doing it this way, a tic/toc before/after the code gives 0.09 seconds; a naive plot as you have, as you have probably seen, gives a runtime of nearly 20 seconds.

Note that I only used get in this example to generate the dataset; I assume for a real time plot you've got some DatasetX and DatasetY to plot, so you'll need to work your data accordingly. But in the end, once you've got the dataset you want to plot at a particular time, just set the line's entire XData and YData.

Finally, note that this set call gets a bit unwieldy for very large datasets, since we have to set the the lines' data every time rather than append to it. (But it's certainly still faster than using plot.) This might be good enough depending on how frequently your dataset changes. See this question for more details.


EDIT: As of MATLAB R2014b, the animinatedline object makes it easier to plot points from streaming data:

Animated line objects optimize line animations by accumulating data from a streaming data source. After you create the initial animated line using the animatedline function, you can add new points to the line without having to redefine the existing points. Modify the appearance of the animated line by setting its properties.

Related Topic