How do I write a loop in MATLAB that continues until the user presses any key?
Show older comments
I want to run a specific routine in a loop. However I want the user to be able to exit the loop and end the routine by pressing any key on the keyboard.
Accepted Answer
More Answers (1)
Xingwang Yong
on 19 Aug 2021
A version uses nested function instead of global variable
function myLoopingFcn2()
KEY_IS_PRESSED = 0;
gcf
set(gcf, 'KeyPressFcn', @myKeyPressFcn)
while ~KEY_IS_PRESSED
drawnow
disp('looping...')
end
disp('loop ended')
function myKeyPressFcn(hObject, event)
KEY_IS_PRESSED = 1;
disp('key is pressed')
end
end
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!