How do you make a callable object?

11 ビュー (過去 30 日間)
Dan Ryan
Dan Ryan 2012 年 6 月 27 日
I want to define a class (much like griddedInterpolant) that has callable objects. Is there a particular method name that is invoked when you attempt to call an object?
For example I would like to be able to do something like:
f = myInterpolationClass(xVals, yVals);
interpolated_values = f(.5:.5:10);
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 6 月 27 日
If necessary you could have the class return a function handle.

サインインしてコメントする。

回答 (1 件)

Kye Taylor
Kye Taylor 2012 年 6 月 27 日
The following class can be used to create a callable object. The key is to overload the subsref function with a class method. Save it in a new classdef file. Instantiate an exampleClass object, then index into this class to see the example's behavior. You can probably figure the rest of what you need from there, but let me know if I can help any further.
classdef exampleClass
methods
% overload subsref
function subsref(obj,S)
if ~all(isnumeric(S.subs{:}))
error('Only supports calling object with number')
end
if numel(S.subs{:}) > 1
disp('You''ve called the object with more than one argument');
else
disp(['You called the object with argument = ',num2str(S.subs{:})]);
end
end
end %methods
end

カテゴリ

Help Center および File ExchangeClass File Organization についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by