Using Timer and Classes
显示 更早的评论
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,
回答(1 个)
per isakson
2012-3-3
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 个评论
bviguier
2012-3-4
Daniel Shub
2012-3-4
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!