how to stop a loop at any time during the loop using ui?

조회 수: 1 (최근 30일)
Orel Levy
Orel Levy 2020년 2월 16일
댓글: Stephen23 2020년 2월 17일
I have a while loop that takes a while to run each iteration, about 60 seconds, and I want to be able to stop the loop at any time witout using CTRL+C.
at the moment I'm using:
ButtonHandle = uicontrol('Style', 'PushButton', ...
'String', 'Stop loop', ...
'Callback', 'delete(gcbf)');
while (ishandle(ButtonHandle))
(run certain processes)
pause(1)
end
While clicking the stop loop button, the loop still doesn't break.
Any idea on how can I use the stop loop button to break the loop?

채택된 답변

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 2월 16일
A possible solution can be done like this:
function gui
fig = figure;
ButtonHandle = uicontrol('Style', 'PushButton', ...
'String', 'Stop loop', ...
'Callback',@StopLoopCallback);
StopLoop = 0;
while true
fprintf('a \n')
pause(1)
if StopLoop
break
end
end
function StopLoopCallback(ob,e)
StopLoop = 1;
end
end
Important is that you constantly ask if the StopLoop was checked, and not only at the end of the while loop, since the function will only be able to stop when the condition is asked. If you have a single function call that takes, for example, 20 s you will not be able to stop it until is over without using ctrl+c option (you could also do it programmatically also but the whole execution will stop in the same way) .
  댓글 수: 2
Orel Levy
Orel Levy 2020년 2월 17일
still doesn't seem to work, what does the "ob,e" means in the function callback?
also, is it neccessery to add the main function gui, or can i run it inside a script?
Stephen23
Stephen23 2020년 2월 17일
"what does the "ob,e" means in the function callback?"
All GUI callback functions are called by default with at least two input arguments, which are the source object and an event array (which may be empty). In the above code neither of them are used within the callback function, so they can be replaced with ~.
Read more:

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by