matlab无法停止,matlab – 如何无限循环,但在某些条件下停止?

对于在满足特定条件时仍可轻松停止的“无限”循环,您可以将

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有两种停止循环的方法:a 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函数工作区中的keepLo​​oping值.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值