How to save output arguments from functions called by timers
7 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Jacob Halbrooks
on 19 Mar 2012
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.
0 Comments
More Answers (1)
Damien T
on 5 Feb 2022
Timers have a "UserData" property for passing data to/from callback functions.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!