How can I make a sum of two numbers update if one of the terms is updated in MATLAB 7.9 (R2009b)?
2 次查看(过去 30 天)
显示 更早的评论
I have calculated a sum of 2 numbers - a and b:
a=3;
b=3;
c=a+b;
I then modify a and would like c to update:
a=4;
c
However, c remains the same, as a, b, and c are of class double which is a value class. How can I write a custom handle class that would implement this functionality?
采纳的回答
MathWorks Support Team
2010-4-13
Define a custom class MYDOUBLE as follows:
classdef mydouble<handle
properties(SetObservable)
value
end
methods
function obj=mydouble(v)
obj.value=v;
end
function update(obj,src,event,c,b)
c.value= obj.value+b.value;
end
end
end
You can then use the following code to update the value of the sum of two numbers:
clear classes
%create 3 mydouble. the 3rd one will be the sum of the first two
a = mydouble(5);
b = mydouble(4);
c = mydouble(a.value+b.value);
% add listeners to objects a and b so that they could listen for the change in their % property 'value' and update the sum c
addlistener(a,'value','PostSet',@(src, event) a.update(src, event,c, b));
addlistener(b,'value','PostSet',@(src, event) b.update(src, event,c, a));
% test the update
c.value
ans =
9
a.value = 15;
c.value
ans =
19
b.value = 30;
c.value
ans =
45
Please refer to the documentation for more information on Defining Events and Listeners:
web([docroot '/techdoc/matlab_oop/brb6gnc.html'])
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!