Print out a warning every whole second in Matlab

我的未来我决定 提交于 2019-12-02 04:40:59

Use a timer object.

t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = 1;
t.TimerFcn = @(~,~)disp('1s elapsed');
start(t)
Amro

As @Daniel suggested, timer objects are the way to go.

One thing to remember is that MATLAB timers execute asynchronously but are not truly parallel (even though timer objects run in a different thread, the MATLAB interpreter is still single-threaded).

So timer events might not fire (BusyMode property defaults to drop) it they occur during certain lengthy non-interruptible operations (like builtin functions, MEX-functions, etc..).

Here is an example:

>> t = timer('ExecutionMode','fixedRate', 'Period',1, 'BusyMode','drop', ...
    'TimerFcn',@(~,~)disp(datestr(now,'MM:SS')));
>> start(t)
35:21
35:22
35:23
>> eig(rand(2000));    % <-- takes a couple of seconds to finish
35:27
35:28
35:29
35:30
>> stop(t)

Note how the timer event did not get a chance to execute while the EIG function was running.

Now if we change the BusyMode property to queue, then once again the event will not fire during the execution of EIG operation, but will immediately spit out all the queued events once EIG finishes:

>> t.BusyMode = 'queue';
>> start(t)
37:39
37:40
>> eig(rand(2000));
37:45
37:45
37:45
37:45
37:45
37:46
37:47
>> stop(t)
>> delete(t)

It is called pause. The optional argument specifies the duration in seconds. Documentation: http://www.mathworks.de/de/help/matlab/ref/pause.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!