Matlab中的“__call__”等效于classdef

时间:2017-10-06 00:26:32

标签: python matlab class object call

是否可以在MATLAB中定义类方法,类似于Python中的“调用”方法?

如何在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)]

1 个答案:

答案 0 :(得分:2)

要在MATLAB中创建"callable"的类对象,您需要修改subsref方法。当您对对象A(i)使用A{i}A.iA等下标索引操作时,会调用此方法。由于调用函数和索引对象都在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