Print out a warning every whole second in Matlab

2019-02-28 10:06发布

问题:

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