how to pause and continue running a for loop
134 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Image Analyst
on 4 Mar 2023
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 Comments
Voss
on 4 Mar 2023
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!