2016-12-03 60 views
1

簡約例子:變換等功能處理,以其他同等功能的處理

classdef MyClass 
properties 
    arr 
    handArr 
end 
properties(Dependent) 
    rowAcc 
    colAcc 
end 
methods 
    function obj = MyClass(arr, handRow, handCol) 
     obj.arr = arr; 
     obj.handArr{1} = handRow; 
     if ~isequal(handRow, handCol) 
      obj.handArr{2} = handCol; 
     end 
    end 
    function r = get.rowAcc(obj) 
     r = obj.handArr{1}(obj.arr); 
    end 
    function c = get.colAcc(obj) 
     c = obj.handArr{end}(obj.arr); 
    end 
end 
end 

現在假設我通過平等函數的構造,我想Row和Col訪問也將是相同的:

[email protected](x)@(y) y; 
x=MyClass(1, f, f); 
isequal(x.rowAcc, x.colAcc) //should be 1 

這可能嗎?

我對這個「瘋狂」的要求的原因是:

我已與輸入的宏塊100+運行,並採取這兩個函數作爲輸入,並且幾種算法當它們相等時,他們可以很優化有效率的;調用我需要對這個類中封裝的輸入函數進行轉換的算法。我無法更改算法(不是我的代碼),他們使用isequal來分配他們自己的函數。

指向同一匿名函數

回答

2

兩個變量被認爲是相等的

f = @(x)x; 
g = f; 

isequal(f, g) 
% 1 

但是,如果你在不同的時間定義匿名函數,那麼他們不被認爲是相等的,因爲的內部工作區兩個功能可能不同。

f = @(x)x; 
g = @(x)x; 

isequal(f, g) 
% 0 

爲了讓你的財產歸還等於手柄,你可以有哪些緩存存取一些「陰影」屬性(accessors_),並更新每當arr屬性更改這些緩存的值。

classdef MyClass 

    properties 
     arr 
     handArr 
    end 

    properties (Access = 'protected') 
     accessors_  % An array of accessor functions for rows & columns 
    end 

    properties (Dependent) 
     rowAcc 
     colAcc 
    end 

    methods 
     function set.arr(obj, value) 
      % Set the value 
      obj.arr = value; 

      % Update the accessors_ 
      self.accessors_ = obj.handArr{1}(obj.arr); 

      % Only assign another accessor if we have a second one 
      if numel(obj.handArr) > 1 
       self.accessors_(2) = obj.handArr{2}(obj.arr); 
      end 
     end 

     function res = get.rowAcc(obj) 
      res = obj.accessors_(1); 
     end 

     function res = get.colAcc(obj) 
      % If only one was stored, this will return a duplicate of it 
      res = obj.accessors_(end); 
     end 
    end 
end 

這也有,你沒有創建功能的額外好處處理每一個colAccrowAcc檢索時間。

+0

再次感謝您的另一個偉大的答案! –