![]() |
如何无限循环,但在某些情况下停止?
我正在使用MATLAB进行项目。它包括连续绘制从计算机的串行端口接收到的有关温度的数据。我想无限地做,所以有什么办法可以像C语言那样创建无限循环?
现在if实现为: while(true) %comments end; 如下面的摩尔所述,那么有什么方法可以更新这些标志,以便可以根据要求或任何其他操作将其终止? 示例:我正在绘制通过ZigBee进行通信的5个节点的数据,然后,如果我选择在Axis上绘制4个节点的数据,那么在启动无限循环之后还有什么办法,以便可以通过循环更改正在循环中使用的数据。 MATLAB GUI的输入法或任何标志? [B]回答:[/B] 对于在满足特定条件时仍然可以轻松停止的“无限”循环,可以将[URL="https://www.mathworks.com/help/matlab/ref/while.html"]while条件[/URL]设置为可以在循环内更新的[URL="https://www.mathworks.com/help/matlab/logical-operations.html"]逻辑变量[/URL] (即标志): 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 如果在循环中遇到[URL="https://www.mathworks.com/help/matlab/ref/break.html"]break[/URL]或[URL="https://www.mathworks.com/help/matlab/ref/return.html"]return[/URL]命令,则while循环也可以终止。 [B]例:[/B] 作为一些您可以停止循环的基于GUI的方式的示例,这是一个程序,该程序创建一个简单的GUI,该GUI连续递增,并使用while循环每秒显示一次计数器。 GUI有两种停止循环的方式:在图形窗口具有焦点时[URL="https://www.mathworks.com/help/matlab/ref/uicontrol.html"]按下按钮[/URL]或按q (使用图形的[URL="https://www.mathworks.com/help/matlab/ref/matlab.ui.figure-properties.html#property_d119e285730"]'KeyPressFcn'属性[/URL]在按下键时运行代码)。只需将此代码保存在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 上述例子利用了[URL="https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html"]嵌套函数[/URL] ,使得'KeyPressFcn'和按钮回调可以访问和修改的值keepLooping在的工作区stop_watch功能。 [url=https://stackoverflow.com/questions/4481708]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 01:05。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.