How do I connect points in a scatter plot with lines inside an infinite loop?

The code I have is meant to run through an infinite while loop to collect and plot incoming data in real time.
Within the loop, it gathers speed and time values and plots them as individual points on a scatter plot. Because the program only has a point to plot each time it runs through the loop, the command plot(time, speed_mph, 'b-') doesn't work. Because the code is supposed to plot in real time, I can't just store the data and plot it outside of the loop.
Is there a way to connect the last plotted point and new plotted point with a line without clearing previous data from the plot?
The current code for plotting is roughly as shown below.
figure(1)
hold on
plot(time, speed_mph, 'b.')
set(gcf, 'Position', [0, 0, 1, 2/3] .* get(0, 'Screensize'));
set(gca, 'Xtick', time, 'XTickLabel', timestring);

 Réponse acceptée

You can use animatedline to do this. See the example code below.
% create an animatedline
speed_line = animatedline('Color','b');
% initialize t
t = 0;
% infinite loop
while true
% get the new time and speed
new_time = t;
new_speed = 100*rand();
% add the new point to the line
addpoints(speed_line,new_time,new_speed);
% update the graphics
drawnow();
% increment t
t = t + 0.1;
end

4 commentaires

Thanks Voss! You're completely right that that's the function I need. However, I'm having trouble with getting the code to run. It's giving me an error with the addpoints function:
Error using matlab.graphics.animation.AnimatedLine/addpoints
Value must be a handle.
Error in GPSsystemdata (line 98)
addpoints(speed_line, time, speed_mph)
I looked into the issue a little bit and found that speed_line isn't valid, even though I have the code to create the animated line before the loop:
speed_line = animatedline('Color','b');
Any idea what might be causing this or what I might need to look into further?
Sounds like speed_line is being deleted by something in the code after the line where speed_line is created and before the line where addpoints(speed_line,___) is called.
Many graphics functions in MATLAB delete existing graphics objects by default. For instance, if you have a plot call after speed_line is created and there is no hold on beforehand, then that plot call would delete speed_line.
Try using hold on right after speed_line is created. If that doesn't work, post the relevant code and I'll see if I can get it sorted out.
You're absolutely right - I had hold on in my code, but a subplot command was messing it up. Thanks so much!
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Graphics Performance dans Centre d'aide et File Exchange

Produits

Version

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by