how to pause and continue running a for loop
조회 수: 134 (최근 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!