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