Print out a warning every whole second in Matlab

前端 未结 3 1497
轮回少年
轮回少年 2021-01-24 04:43

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 loo

相关标签:
3条回答
  • 2021-01-24 05:14

    Use a timer object.

    t = timer;
    t.ExecutionMode = 'fixedRate';
    t.Period = 1;
    t.TimerFcn = @(~,~)disp('1s elapsed');
    start(t)
    
    0 讨论(0)
  • 2021-01-24 05:23

    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)
    
    0 讨论(0)
  • 2021-01-24 05:34

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

    0 讨论(0)
提交回复
热议问题