"__call__" 在 Matlab classdef 中等效

"__call__" equivalent in Matlab classdef

是否可以在 MATLAB 中定义一个类似于 Python 中的“call”方法的 class 方法?

您将如何在 MATLAB 中实现以下 Python class。

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)]

在 MATLAB 中创建一个 class 对象 "callable", you would need to modify the subsref method. This is the method that is called when you use subscripted indexing operations like A(i), A{i}, or A.i for object A. Since calling a function and indexing an object both use () in MATLAB, you would have to modify this method to mimic callable behavior. Specifically, you would likely want to define () indexing to exhibit callable behavior for a scalar obect,但对非标量对象表现出正常的 vector/matrix 索引。

这是一个示例 class (using 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