對於一個「無限」循環,仍然可以很容易地停在特定條件得到滿足,你可以設置你的while condition是一個logical variable(即標誌),可你的循環內進行更新:
keepLooping = true; % A flag that starts as true
while keepLooping
% Read, process, and plot your data here
keepLooping = ...; % Here you would update the value of keepLooping based
% on some condition
end
如果在循環中遇到break
或return
命令,則也可以終止while循環。
例:
由於一些基於GUI的方法的例子,你可以停止循環,這裏是創建一個簡單的圖形用戶界面,不斷增加並顯示一個計數器每秒一次的程序使用一個while循環。 GUI有兩種停止循環的方法:一個push button或按q而數字窗口有焦點(使用圖的'KeyPressFcn'
property按鍵時運行代碼)。就在某個地方將這段代碼保存在M文件MATLAB的路徑,並運行它來測試的例子:
function stop_watch
hFigure = figure('Position', [200 200 120 70], ... % Create a figure window
'MenuBar', 'none', ...
'KeyPressFcn', @stop_keypress);
hText = uicontrol(hFigure, 'Style', 'text', ... % Create the counter text
'Position', [20 45 80 15], ...
'String', '0', ...
'HorizontalAlignment', 'center');
hButton = uicontrol(hFigure, 'Style', 'pushbutton', ... % Create the button
'Position', [20 10 80 25], ...
'String', 'Stop', ...
'HorizontalAlignment', 'center', ...
'Callback', @stop_button);
counter = -1;
keepLooping = true;
while keepLooping % Loop while keepLooping is true
counter = counter+1; % Increment counter
set(hText, 'String', int2str(counter)); % Update the counter text
pause(1); % Pause for 1 second
end
%---Begin nested functions---
function stop_keypress(hObject, eventData)
if strcmp(eventData.Key, 'q') % If q key is pressed, set
keepLooping = false; % keepLooping to false
end
end
function stop_button(hObject, eventData)
keepLooping = false; % Set keepLooping to false
end
end
上面的例子利用了nested functions,使得'KeyPressFcn'
和按鈕的回調可以訪問和修改的值keepLooping
在stop_watch
函數的工作區中。
請注意,如果沒有「暫停」(暫停),這將不起作用,它將完成循環,然後處理排隊的回調事件,從而達到目的。請注意,它是實際處理隊列和'暫停'調用'drawnow'(或者等效)的'drawnow'命令,因此出於可讀性的原因,最好在'pause'旁邊明確添加'drawnow'。 – 2013-05-09 06:46:01
我遇到了這個問題,因爲我正在使用更準確的方式來等待,基於'java.lang.Thread.sleep(..)'或'Object.wait(..)'和'java.lang.Thread。 yield()',這與'pause'不同,因爲這些方法不包括對'drawnow'(或等價物)的附屬調用。 – 2013-05-09 06:49:00