Using Timer and Classes
Show older comments
I would like to use a timer to update the property (updateME)of a class using the function (updateMEFct). The way i did is not working properly and it certainly has to do on how i called the function in the timer (@(x,y)td.updateMEFct(td)). The function call of the timer should overwrite the instance of the class, but i don't know how to do that in this context.
here is the class :
classdef Updates
properties
t;
updateME;
end
methods
%constructor
function td = Updates(period)
td.updateME=100000;
td.t = timer('TimerFcn',@(x,y)td.updateMEFct(), 'Period', period, ...
'ExecutionMode', 'fixedRate');
end
function td=updateMEFct(td)
td.updateME=rand();
end
function start(td)
start(td.t);
end
function stop(td)
stop(td.t);
end
end
end
to launch the timer i used:
XX=Updates(5);
XX.start;
when i do that, updateME stays at 100000. if i call directly the function:
XX=XX.updateMEFct()
updateME changes.
Thanks for your help,
Answers (1)
per isakson
on 3 Mar 2012
The problem is that it is a value class and that you don't keep the updated object.
classdef Updates < handle
makes it work as you expect.
===============
Update:
With a value class it is possible to use assignin to save the updated object. However, to me that smells. I don't know if there is a "clean" way to do it.
function td=updateMEFct(td )
td.updateME=rand();
disp( [ datestr( now, 31 ), ': ', num2str( td.updateME ) ] )
assignin( 'base', 'XX', td )
end
>> clear all
clear classes
XX=Updates(5);
XX.start;
2012-03-04 01:37:18: 0.25108
2012-03-04 01:37:23: 0.61604
2012-03-04 01:37:28: 0.47329
>> XX
XX =
Updates
Properties:
t: []
updateME: 0.4733
Methods
/ per
2 Comments
bviguier
on 4 Mar 2012
Daniel Shub
on 4 Mar 2012
Can you move the update about the handle class higher to the beginning of the answer, as to me that seems to be the answer. Your comment that the original code works is seems to be a red herring.
Categories
Find more on Whos 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!