How to save output arguments from functions called by timers

8 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by