繁体   English   中英

Matlab classdef中的“ __call__”等效项

[英]“__call__” equivalent in Matlab classdef

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

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

要在MATLAB中创建“可调用”的类对象,您需要修改subsref方法。 当对对象A使用下标索引操作(例如A(i)A{i}Ai A(i)A{i}调用此方法。 由于在MATLAB中调用函数和为对象建立索引都使用() ,因此您必须修改此方法以模仿可调用行为。 具体来说,您可能希望定义()索引以显示标量对象的可调用行为,但显示非标量对象的法向矢量/矩阵索引。

这是一个示例 (使用此文档定义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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM