How to generate an event in matlab every second

48 ビュー (過去 30 日間)
Angela Muñoz
Angela Muñoz 2018 年 4 月 21 日
コメント済み: Angela Muñoz 2018 年 4 月 21 日
Hi, I want to generate an event in Matlab every second and execute the function depending on it, how can I do it? Thank you very much!
  2 件のコメント
Walter Roberson
Walter Roberson 2018 年 4 月 21 日
Do you want the event to be generated every real-time second, or do you want it to be generated every simulated second?
What do you want to have happen to event generation when you pause the program for debugging (as you will surely need to do) ?
Angela Muñoz
Angela Muñoz 2018 年 4 月 21 日
I want it to be generated every simulated second and depending on the input do an action or another

サインインしてコメントする。

回答 (2 件)

Stephen23
Stephen23 2018 年 4 月 21 日
編集済み: Stephen23 2018 年 4 月 21 日
  1 件のコメント
Angela Muñoz
Angela Muñoz 2018 年 4 月 21 日
Thank you very much for the info!

サインインしてコメントする。


Ameer Hamza
Ameer Hamza 2018 年 4 月 21 日
編集済み: Ameer Hamza 2018 年 4 月 21 日

You can setup up a timer class object to repeat a task at a fixed time rate. The simple way to create a timer object is

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

If you are using recent versions of MATLAB you can also use dot notation to specify timer properties

t = timer()
t. ExecutionMode = 'fixedRate'
t.Period = 1;
t.TimerFcn = @(~,~) disp('1s passed'); % you can use function handle or an anonymous function.

The TimerFcn is a callback function executed after each period of time. It must accept two or more inputs. First two inputs are used for accessing timer object handle and Event type. For most simple purposes first two inputs can be ignored. If you want to pass an additional input to TimerFcn you can use following notation

str = 'passed';
t.TimerFcn = {@(~,~,x) disp(['1s ' x]), str};

In this case, the timer Callback function will access the variable named str from base workspace. A more advanced example of timer callback function is

t.TimerFcn = {@(tObj,~,x) disp([num2str(tObj.Period) 's ' x]), str};

Here the callback function can also use the timer object handle and access its property using dot notation.

  1 件のコメント
Angela Muñoz
Angela Muñoz 2018 年 4 月 21 日
Thank you very much I will surely try out!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by