フィルターのクリア

How do I write a loop in MATLAB that continues until the user presses any key?

86 ビュー (過去 30 日間)
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.

採用された回答

MathWorks Support Team
MathWorks Support Team 2010 年 2 月 5 日
MATLAB does not have a function that scans for keyboard activity without interrupting the event stream.
However, if your program involves a figure window, you can utilize the ‘KeyPressFcn’ property. The 'KeyPressFcn' is called when a key is pressed with an active figure window. You can set this function to change the state of a flag that ends a loop. Copy the following functions to a MATLAB file, and execute the MATLAB file.
function myLoopingFcn()
global KEY_IS_PRESSED
KEY_IS_PRESSED = 0;
gcf
set(gcf, 'KeyPressFcn', @myKeyPressFcn)
while ~KEY_IS_PRESSED
drawnow
disp('looping...')
end
disp('loop ended')
function myKeyPressFcn(hObject, event)
global KEY_IS_PRESSED
KEY_IS_PRESSED = 1;
disp('key is pressed')
The code will display "looping" in the MATLAB Command Window until a key is pressed when the figure window is active.

その他の回答 (1 件)

Xingwang Yong
Xingwang Yong 2021 年 8 月 19 日
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

カテゴリ

Help Center および File ExchangeDesktop についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by