How to use a timer to call a function, and assign it's output to a variable in the work space
5 views (last 30 days)
Show older comments
Hello,
I'm a new user, and I want to use a timer to call a function, and take that function's output argument to the main code.
I'v tried the following code, but it only prints the output value to the screen. Am I using the correct timer format? Please help.
assignin('base','A',1);
t = timer('TimerFcn', '[A] =time( A )', ...
'StartFcn', @(~,~)fprintf('AAA. %d \n',34)); % timer is defined
fTime = now + 5/(3600*24); % Timer is set for 5 sec (in serial time)Matlab
startat(t,fTime);
if A==2
C=A*4
end
function [ A ] = time( A )
A=A+1;
end
0 Comments
Answers (1)
Deepak
on 9 Jan 2025
We can use a MATLAB timer to periodically call a function that increments a variable and updates it in the base workspace. By setting the "TimerFcn" as a function handle, we can retrieve and modify the variable using "evalin" and "assignin", ensuring the main code accesses the updated value. Using "wait(t)" synchronizes the script until the timer finishes, and cleaning up with "stop" and "delete" releases resources.
Below is the MATLAB code to achieve the same:
% Initialize variable A in the base workspace
assignin('base', 'A', 1);
% Define the timer
t = timer('TimerFcn', @(~,~) updateVariable(), ...
'StartFcn', @(~,~) fprintf('AAA. %d \n', 34));
% Set the timer to start after 5 seconds
fTime = now + 5/(3600*24); % Timer is set for 5 sec (in serial time)
startat(t, fTime);
% Wait for the timer to execute
wait(t);
% Check the updated value of A in the base workspace
A = evalin('base', 'A');
if A == 2
C = A * 4;
fprintf('C = %d\n', C);
end
% Clean up the timer
stop(t);
delete(t);
% Function to update variable A
function updateVariable()
A = evalin('base', 'A'); % Get current value of A
A = A + 1; % Increment A
assignin('base', 'A', A); % Assign updated A back to base workspace
end
Please find attached the documentation of funcitons used for reference:
I hope this helps in resolving the issue.
1 Comment
Walter Roberson
on 9 Jan 2025
"and take that function's output argument to the main code."
That part is not possible. Timer callbacks are executed from inside the base workspace and so cannot write into the workspace of the main code.
See Also
Categories
Find more on Programming Utilities in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!