Print out a warning every whole second in Matlab

允我心安 提交于 2019-12-31 04:51:08

问题


I am trying to print a warning or just a message after every second, like "1 second elapsed". Is there a possibility to realize that?

I tried it with tic toc and a loop, but it is pretty insufficient. Furthermore I never get exactly one second. Is there a command that prints every X ms automatically? Any ideas?

Thanks in advance.


回答1:


Use a timer object.

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



回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/24060288/print-out-a-warning-every-whole-second-in-matlab

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