Azzera filtri
Azzera filtri

how to pause and continue running a for loop

119 visualizzazioni (ultimi 30 giorni)
Faith
Faith il 4 Mar 2023
Risposto: Voss il 4 Mar 2023
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?

Risposte (2)

Image Analyst
Image Analyst il 4 Mar 2023
Use msgbox or helpdlg enclosed in a uiwait.
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
You could also use questdlg if you want to give the user a chance to break out of the loop:
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

Voss
Voss il 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

Categorie

Scopri di più su Environment and Settings in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by