lines()
or points()
will add to the existing graph, but will not create a new window. So you'd need to do
plot(x,y1,type="l",col="red")
lines(x,y2,col="green")
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.
Best Answer
As Edric mentioned, you'll definitely want to include a
drawnow
command after the call toplot
to force an update of the graphics. However, there is a much more efficient and smoother method to animate plots that doesn't involve recreating the entire plot each time. You can simply initialize your plot, capture a handle to the plot object, then modify the properties of that object in your loop using theset
command. Here's an example:In addition, before your loop and after the call to
plot
you can set a number of axes properties, like the axes limits, etc., if you want the axes to stay fixed and not change their appearance with each new vectorm
that is plotted.