2017-10-06 61 views
1

是否有可能在MATLAB中定義類方法類似於「調用」方法?「__call__」在Matlab中相當於classdef

您將如何在MATLAB中實現以下Python類。

class Basic(object): 

    def __init__(self, basic): 
     self.basic = basic 

    def __call__(self, x, y): 
     return (numpy.sin(y) *numpy.cos(x)) 

    def _calc(self, y, z): 
     x = numpy.linspace(0, numpy.pi/2, 90) 
     basic = self(x, y) 
     return x[tuple(basic< b).index(False)] 

回答

2

要創建MATLAB類對象,它是"callable",你將需要修改subsref方法。這是在對對象A使用下標索引操作(如A(i),A{i}A.i)時調用的方法。由於調用一個函數並建立一個對象索引都在MATLAB中使用(),你將不得不修改這個方法來模仿可調用的行爲。具體而言,您可能想要定義()索引以展現scalar obect的可調用行爲,但展示非標量對象的法向矢量/矩陣索引。

這裏的class(使用this documentation定義subsref方法)的樣本,其提高其屬性設置爲電源進行贖回行爲:

classdef Callable 

    properties 
    Prop 
    end 

    methods 

    % Constructor 
    function obj = Callable(val) 
     if nargin > 0 
     obj.Prop = val; 
     end 
    end 

    % Subsref method, modified to make scalar objects callable 
    function varargout = subsref(obj, s) 
     if strcmp(s(1).type, '()') 
     if (numel(obj) == 1) 
      % "__call__" equivalent: raise stored value to power of input 
      varargout = {obj.Prop.^s(1).subs{1}}; 
     else 
      % Use built-in subscripted reference for vectors/matrices 
      varargout = {builtin('subsref', obj, s)}; 
     end 
     else 
     error('Not a valid indexing expression'); 
     end 
    end 

    end 

end 

這裏有一些用法示例:

>> C = Callable(2) % Initialize a scalar Callable object 

C = 
    Callable with properties: 
    Prop: 2 

>> val = C(3) % Invoke callable behavior 

val = 
    8   % 2^3 

>> Cvec = [Callable(1) Callable(2) Callable(3)] % Initialize a Callable vector 

Cvec = 
    1×3 Callable array with properties: 
    Prop 

>> C = Cvec(3) % Index the vector, returning a scalar object 

C = 
    Callable with properties: 
    Prop: 3 

>> val = C(4) % Invoke callable behavior 

val = 
    81   % 3^4