我正在使用MATLAB进行项目。它包括连续绘制从计算机的串行端口接收到的有关温度的数据。我想无限地做,所以有什么办法可以像C语言那样创建无限循环?
现在if实现为:
while(true) %comments end; 如下面的摩尔所述,那么有什么方法可以更新这些标志,以便可以根据要求或任何其他操作将其终止?
示例:我正在绘制通过ZigBee进行通信的5个节点的数据,然后,如果我选择在Axis上绘制4个节点的数据,那么在启动无限循环之后还有什么办法,以便可以通过循环更改正在循环中使用的数据。 MATLAB GUI的输入法或任何标志?
回答:
对于在满足特定条件时仍然可以轻松停止的“无限”循环,可以将
while条件设置为可以在循环内更新的
逻辑变量 (即标志):
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,该GUI连续递增,并使用while循环每秒显示一次计数器。 GUI有两种停止循环的方式:在图形窗口具有焦点时
按下按钮或按q (使用图形的
'KeyPressFcn'属性在按下键时运行代码)。只需将此代码保存在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 上述例子利用了
嵌套函数 ,使得'KeyPressFcn'和按钮回调可以访问和修改的值keepLooping在的工作区stop_watch功能。
更多&回答...