Condition for if-statement not updating inside for-loop without pause function

Hello!
I want to break from a for-loop when I close a plot. This is the code I use:
cscale = 100; %The number of colours in the colormap of choice
for c2 = 1:length(time)
f2 = figure(2);
p = plot(G);
G.Nodes.value = floor(real(cos(x(:,c2))+1)*((cscale-1)/2))+1; %scales x values to range from 1 up to cscale.
G.Edges.value = floor(real(cos(y(:,c2))+1)*((cscale-1)/2))+1; %scales y values to range from 1 up to cscale.
G.Nodes.NodeColors = G.Nodes.value;
G.Edges.EdgeColors = G.Edges.value;
p.NodeCData = G.Nodes.NodeColors;
p.EdgeCData = G.Edges.EdgeColors;
colormap(flipud(turbo(cscale)));
pause(1/5000);
if ~isgraphics(f2)
break;
end
end
The for-loop is not inside any other loop, so I shouldn't need to break more than once to end the code. The above only worked when I introduced the pause function, no matter how short the pause is. Note that I tried changing the condition to ~isgraphics(f1) where f1 is another figure generated earlier in the code (unlike f2, f1 is not generated inside a loop), and I also tried ishghandle and ishandle, but without the pause function, they all kept returning a logical 0 even after I closed the figure, and hence the code didn't break the loop. My question is why does it not work without pausing?
Any insight would be appreciated!

2 Kommentare

Try with handle to plot function (without pause)
if ~isgraphics(p)
break;
end
@VBBV thanks for the suggestion. However, I forgot to mention that I tried that as well and it didn't work. I still need the pause function.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Matt J
Matt J am 21 Apr. 2024
Bearbeitet: Matt J am 21 Apr. 2024
A more standard solution is to use drawnow rather than pause.
for c2 = 1:length(time)
f2 = figure(2);
...
drawnow
if ~isgraphics(f2)
break;
end
end
The reason these things are necessary is that graphics operations are executed asynchronously with Matlab code. In other words, the rest of the code is allowed to proceed once a graphics instruction is deployed, even if the graphics instruction has not finished executing. This is for performance optimization purposes. Certain commands like drawnow and pause introduce barrier points that prevent the code from proceeding until all graphics have updated, see also here.

Weitere Antworten (0)

Kategorien

Mehr zu Graphics Performance finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by