MATLAB: How to pass variables between timer callback functions

MATLAB

I have a timer and I initialise data in the StartFcn callback and manipulate that data in my TimerFcn callback. However, these callbacks have different scopes, and each time the TimerFcn is evaluated the workspace is cleared.
Is there a way of passing data between my StartFcn callback and the TimerFcn callback? And how can I have my TimerFcn manipulate the same variables each time without having to use persistent variables?

Best Answer

As described in our Timer Callback documentation here:
timer callbacks need their function declaration in the form:
function processing(src, event)
The "src" variable is actually the timer object that calls the callback. The TIMER class has a property called "UserData" which you can set to whatever value you want. If you have a lot of data you want to pass between functions, you could set this to be a structure or cell array containing all the variables you need to pass around.
See:
Here is some example code demonstrating this process:
function MakeTimer()
t=timer;
t.StartFcn = @initTimer;
t.TimerFcn = @timerCallback;
t.Period = 0.5;
t.TasksToExecute = 5;
t.ExecutionMode = 'fixedRate';
start(t);
wait(t);
delete(t);
end
function initTimer(src, event)
src.UserData = 0;
disp('initialised')
end
function timerCallback(src, event)
src.UserData = src.UserData + 1;
disp(src.UserData)
end
This will output:
>> MakeTimer
initialised
1
2
3
4
5
Another option, would be to make the callbacks nested functions of MakeTimer. Nested functions use the same workspace as the parent function, so all variables are accessible.
See:
Here is an example of using nested functions as timer callbacks:
function MakeTimer()
   myVar = [];
   t=timer;
   t.StartFcn = @initTimer;
   t.TimerFcn = @timerCallback;
   t.Period   = 0.5;
   t.TasksToExecute = 5;
   t.ExecutionMode  = 'fixedRate';
   start(T);
   wait(T);
   delete(T);
   
   function initTimer(src, event)
        myVar = 0;
        disp('initialised')
    end
 
    function timerCallback(src, event)
       myVar = myVar + 1;
       disp(myVar)
    end
end