Filter löschen
Filter löschen

How to save output arguments from functions called by timers

8 Ansichten (letzte 30 Tage)
Kirk
Kirk am 19 Mär. 2012
Beantwortet: Damien T am 5 Feb. 2022
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.

Akzeptierte Antwort

Jacob Halbrooks
Jacob Halbrooks am 19 Mär. 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.

Weitere Antworten (1)

Damien T
Damien T am 5 Feb. 2022
Timers have a "UserData" property for passing data to/from callback functions.

Kategorien

Mehr zu Migrate GUIDE Apps finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by