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.
shg makes the current figure visible and places it in front of all other figures on the screen. This is identical to using the command figure(gcf) .
drawnow updates figures and processes any pending callbacks. Use this command if you modify graphics objects and want to see the updates on the screen immediately. example. drawnow limitrate limits the number of updates to 20 frames per second.
Update Plot Using Data LinkingCreate the variable x to represent the iteration number and y to represent the approximation. Plot the initial values of x and y . Turn on data linking using linkdata on so that the plot updates when the variables change. Then, update x and y in a for loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With