How to break out of a while loop inside a function block ?

조회 수: 6 (최근 30일)
Prashanth Krishnan
Prashanth Krishnan 2015년 7월 28일
댓글: Camile van der Heijden 2018년 3월 1일
I'm trying to break out of a while loop when a key is pressed and I've achieved this through the following code snippet -
keep = 1;
h = figure('KeyPressFcn','keep=0');
while keep
pause(0.01)
end
close(h)
I need to incorporate this into a GUI. But when this exact same code snippet is inserted into a function block, I'm no longer able to break out of the loop. Here's a code for the same -
function calibrate()
keep = 1;
h = figure('KeyPressFcn','keep=0');
while keep
pause(0.01)
end
close(h)
How do I get this to work ?
Thanks !
  댓글 수: 1
Muthu Annamalai
Muthu Annamalai 2015년 7월 28일
Please use {} Code editor feature to make your code more readable to others.

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

채택된 답변

Jon
Jon 2015년 7월 28일
편집: Jon 2015년 7월 28일
The search function is your friend. See https://ch.mathworks.com/matlabcentral/newsreader/view_thread/315080 for someone with the same problem, and an explanation and solution.
  댓글 수: 2
Prashanth Krishnan
Prashanth Krishnan 2015년 7월 28일
Thanks Jon! This worked like a dream.
Camile van der Heijden
Camile van der Heijden 2018년 3월 1일
Unfortunately, the newsreader link Jon referred to is no longer available. I would love to know what it said though. Does it involve using flag variables?

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

추가 답변 (1개)

Muthu Annamalai
Muthu Annamalai 2015년 7월 28일
편집: Muthu Annamalai 2015년 7월 28일
Changing your code to,
keep = true;
h = figure('KeyPressFcn',@() keep= ~keep );
while keep
pause(0.01)
sprintf('keep = %d',keep);
end
close(h)
may work. If this doesn't work, make keep an instance of a handle class.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by