How to save output arguments from functions called by timers

7 ビュー (過去 30 日間)
Kirk
Kirk 2012 年 3 月 19 日
回答済み: Damien T 2022 年 2 月 5 日
Hello guys, I have a question I'm sure you guys can solve in about 5 seconds. Suppose I have the following function:
function z = executethis(t,c)
z =randn();
end
Suppose also that I have the following timer object defined: t=timer('TimerFcn',@(t,c,x)executethis,'Period',2,'ExecutionMode','fixedRate')
which I then initiate with start(t).
I want to save the output argument from the function every 2 seconds into a vector in my workspace. However, I'm not sure how to do this. Any help will be appreciated.
Thank you.

採用された回答

Jacob Halbrooks
Jacob Halbrooks 2012 年 3 月 19 日
A simple option to communicate between your program and timer callback is to make the timer callback a nested function in your main function. This gives it direct access to variables in the workspace. For example:
function dotimer
counter = 0;
t=timer('TimerFcn', @(h,~)onTimerCallback(h), ...
'Period', 2, 'ExecutionMode', 'fixedRate');
start(t);
pause(5);
stop(t);
disp(counter);
function onTimerCallback(h)
counter = counter + 1;
end
end
If your timer callback is located in a different file from the rest of your program logic, consider writing a handle class that would facilitate communication. This class might be a good place to house much of your model logic. When you create your timer, you would pass the object instance to the timer callback, which could set properties or call methods on it:
obj = MyModel;
t=timer('TimerFcn', @(~,~)onTimerCallback(obj), ...
'Period', 2, 'ExecutionMode', 'fixedRate');
function onTimerCallback(obj)
obj.counter = obj.counter + 1;
obj.update();
end
Instead of creating a new class, you might also be able to re-use a handle object from your application and use SETAPPDATA and GETAPPDATA.
Lastly, you could also use a GLOBAL variable.

その他の回答 (1 件)

Damien T
Damien T 2022 年 2 月 5 日
Timers have a "UserData" property for passing data to/from callback functions.

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by