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 件のコメント

VBBV
VBBV 2024 年 4 月 21 日
Try with handle to plot function (without pause)
if ~isgraphics(p)
break;
end
Ahmed Amer Abdullah Zaid
Ahmed Amer Abdullah Zaid 2024 年 4 月 21 日
@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.

サインインしてコメントする。

 採用された回答

Matt J
Matt J 2024 年 4 月 21 日
編集済み: Matt J 2024 年 4 月 21 日
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.

1 件のコメント

Ahmed Amer Abdullah Zaid
Ahmed Amer Abdullah Zaid 2024 年 4 月 21 日
This makes sense, and drawnow works as well. Thank you very much @Matt J!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGraphics Performance についてさらに検索

製品

リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by