How do I get the plot in my for loop to retain previous plots?

68 views (last 30 days)
I'm trying to set up a for loop inside a function to plot my data so I can see it evolving. Here's the relevant code. My function updates 'T'; z is just a vector of the same length.
% Plot every hundredth iteration; this is so I can see if it's changing.
c = c + 1;
if c == 100
c = 0;
fig = figure(1);
axh = axes;
plot(axh,T,z)
hold all
grid on
set(gca,'YDir','Reverse')
title('Evolving Geotherm')
xlabel('Temperature (K)'); ylabel('Depth (m)')
end
This will display ONLY the latest data; none of the previous plots remain. I get the same results when I use 'hold on' and 'drawnow'. This seems like a really simple bit of code.
What's going on here? Why won't the previous plots remain?

Accepted Answer

Chris
Chris on 28 Oct 2021
Edited: Chris on 28 Oct 2021
You are regenerating the figure and axes every time the if condition triggers. About the only thing you need inside the if is the plot() command. The other stuff should go before the for loop (but inside the function).
fig = figure(1);
axh = axes
hold all
grid on
set(gca,'YDir','Reverse')
title('Evolving Geotherm')
xlabel('Temperature (K)'); ylabel('Depth (m)')
c = 0;
for idx = 1:whatever
% Do some loop stuff...
c = c+1;
if c == 100
c = 0;
plot(axh,T,z)
end
end
  6 Comments
Joshua Knicely
Joshua Knicely on 3 Nov 2021
@Chris & @Jeff Miller, y'all were correct about the drawnow. With that, it shows my plot as the data changes.
@Chris, not sure about meaning with the function scope. Would that be like an accidental recursive call of the function on itself? My data is updated in the for loop.
Chris
Chris on 3 Nov 2021
I was searching for other reasons it could be failing. If the function were calculating one point each time it's called, over repeated calls, it might not have access to all points to pass to plot. I was stretching my imagination a bit, since I couldn't see how the function was working.

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!