我怎样才能无限循环,但在某些条件下停止?

问题描述 投票:8回答:2

我正在MATLAB中开展一个项目。它包括连续绘制从计算机串行端口接收的温度数据。我想无限地去做,所以有没有办法像C一样创建无限循环?

现在如果实现为:

while(true)
%comments
end;

正如摩尔所述,那么有没有办法更新标志,以便根据要求或任何其他操作终止它?

示例:我正在绘制通过ZigBee进行通信的5个节点的数据,然后如果我选择在Axis上绘制4个节点,那么在启动无限循环之后是否有任何方法可以更改循环中使用的数据通过MATLAB的GUI输入法还是任何标志?

matlab loops
2个回答
10
投票

对于在满足某个条件时仍然可以轻松停止的“无限”循环,您可以将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

如果在循环中遇到breakreturn命令,也可以终止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'和按钮回调可以访问和修改keepLooping函数工作区中stop_watch的值。


3
投票
while (true)
    % block of code here
end
© www.soinside.com 2019 - 2024. All rights reserved.