1

Is it possible to define a class method in MATLAB similar to the "call" method in Python?

How would you implement the following Python class in MATLAB.

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)]
adder
  • 3,512
  • 1
  • 16
  • 28
hko
  • 139
  • 3
  • 10

1 Answers1

2

To create a class object in MATLAB that is "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, but exhibit the normal vector/matrix indexing for non-scalar objects.

Here's a sample class (using this documentation for defining subsref methods) which raises its property to a power for its callable behavior:

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

And here are some usage examples:

>> 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
gnovice
  • 125,304
  • 15
  • 256
  • 359