how to pause and continue running a for loop
127 次查看(过去 30 天)
显示 更早的评论
I have a for loop that runs an animation. I don't want anything to reset, but I need to be able to pause my loop and then continue. I don't have any specifications for how to go about this. I've tried using uicontrols and have not been successful yet. Any suggestions?
0 个评论
回答(2 个)
Image Analyst
2023-3-4
for k = 1 : 10000000
condition = whatever you need to pause the loop.........
if condition
% Wait for user to click OK before continuing with the loop.
uiwait(helpdlg('Click OK to continue'))
end
end
message = sprintf('Do you want to continue?');
for k = 1 : 10000000
condition = whatever you need to pause the loop.........
if condition
buttonText = questdlg(message, 'Continue?', 'Yes', 'No', 'Yes');
drawnow; % Refresh screen to get rid of dialog box remnants.
if contains(buttonText, 'No')
break;
end
end
end
0 个评论
Voss
2023-3-4
Here's a simple GUI with an animated line. The for loop adds one random point to the line in each iteration. The button can be used to pause and resume the loop.
You can run it and see how it works. In this case the button's callback function cb_btn is nested inside the main function, but you don't have to do it that way. If you're using GUIDE, you can include the is_paused variable in your handles structure, or if you're using App Designer, include is_paused as a property of your app. The logic is the same in all cases.
Also, note that drawnow is necessary for the button's callback to be able to interrupt the running for loop.
function test_gui
f = figure();
ax = axes(f);
l = animatedline(ax,0,0);
btn = uicontrol(f, ...
'Style','pushbutton', ...
'String','Pause', ...
'Callback',@cb_btn);
is_paused = false;
for ii = 1:1e4
[~,y] = getpoints(l);
addpoints(l,ii,y(end)+randn());
drawnow;
end
function cb_btn(~,~)
if is_paused
set(btn,'String','Pause');
is_paused = false;
uiresume(f);
else
set(btn,'String','Resume');
is_paused = true;
uiwait(f);
end
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!