2012-10-03 71 views
1

作爲MATLAB新手,我正在嘗試編寫一個類,如果兩個屬性中的一個更改了值,則會自動重新計算第三個屬性。自動更新的Matlab屬性

看來事件和聽衆是爲此而做的,但我無法得到他們基本實現的竅門。

我的最新嘗試是這樣的

% when property a or b is altered, c will automatically be recalculated 

classdef myclass < handle 
    properties 
     a = 1; 
     b = 2; 
     c 
    end 

    events 
     valuechange 
    end 

    methods 

     function obj = myclass() 
      addlistener(obj,'valuechange', obj.calc_c(obj)) 
     end 

     function set_a(obj, input) 
      obj.a = input; 
      notify(obj, valuechange) 
     end 

     function set_b(obj, input) 
      obj.b = input; 
      notify(obj, valuechange) 

     end 

     function calc_c(obj) 
      obj.c = obj.a + obj.b 
     end 
    end 
end 

它返回以下錯誤

Error using myclass/calc_c 
Too many output arguments. 
Error in myclass (line 18) 
      addlistener(obj,'valuechange', obj.calc_c(obj)) 

我在做什麼錯?

+0

看來我要找的是這裏所描述的功能:http://stackoverflow.com/questions/8098935/matlab-dependent-properties-and-calculation?rq= 1 – user1361521

+0

我也在這裏發佈了一個監聽器/觀察器的例子:http://stackoverflow.com/questions/9153044/is-it-possible-to-do-stateless-programming-in-matlab-how-to-avoid-checking- d/9153153#9153153 – bdecaf

回答

1

難道你不希望將c定義爲Dependent,以便每次使用它時都確定它已被更新?

像這樣的事情

classdef myclass < handle 
    properties 
     a 
     b 
    end 
    properties (Dependent) 
     c 
    end 

    methods 
    function x = get.x(obj) 
     %Do something to get sure x is consistent 
     x = a + b; 
    end 
end