MATLAB: How to implement a MATLAB class that simulates function syntax (like scatteredInterpolant)

MATLABoop

How can I implement a MATLAB class that simulates function syntax (like 'scatteredInterpolant')? For example,
>> F = MyFunction([91; 13; 92], [64; 10; 28], [55; 96; 97]);
>> F(1, 2)
ans =
101.9511

Best Answer

You can achieve this behavior using operator overloading:
Here is an example 'MyFunction' class that simulates a subset of the behavior of 'scatteredInterpolant' by using a private 'scatteredInterpolant' object and overloading the 'subsref' method.
% MyFunction.m
classdef MyFunction
properties (Access = private)
F
end
methods
function obj = MyFunction(x, y, v)
obj.F = scatteredInterpolant(x, y, v);
end
function B = subsref(A, S)
if ~( ...
strcmp(S.type, '()') && ...
length(S.subs) == 2 && ...
isa(S.subs{1}, 'double') && ...
isa(S.subs{2}, 'double') && ...
all(size(S.subs{1}) == size(S.subs{2})) ...
... % etc.
)
error('error: invalid index ...');
end
B = A.F(S.subs{1}, S.subs{2});
end
end
end
You can use 'MyFunction' as follows.
>> F = MyFunction([91; 13; 92], [64; 10; 28], [55; 96; 97])
F =
MyFunction with no properties.
>> F(1, 2)
ans =
101.9511
>> F([1; 2], [1; 2])
ans =
103.1101
102.2278
>> F([1 2], [1 2])
ans =
103.1101 102.2278
Note that you could implement the 'subsref' method to support multiple numbers and types of indices (as 'scatteredInterpolant' does).