2016-12-03 9 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 

지금은 행 및 COL 액세스 같은 것 원하는 I 생성자 동등한 기능을 전달 가정

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

가능합니까? 그들이 동일한 경우

I 입력의 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

또 다른 멋진 답변을 보내 주셔서 감사합니다. –