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!