对于在满足特定条件时仍然可以轻松停止的“无限”循环,您可以将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 的方法的示例,这里有一个程序,它创建了一个简单的 GUI,它使用 while 循环每秒连续递增并显示一个计数器。 GUI 有两种停止循环的方法:push button 或在图形窗口具有焦点时按 q(使用图形的 'KeyPressFcn' property 在按下键时运行代码)。只需将此代码保存在 MATLAB 路径上某处的 m 文件中并运行它来测试示例:
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'和按钮回调可以访问和修改stop_watch函数工作区中keepLooping的值。