nargout with class method handles

2 ビュー (過去 30 日間)
Markus Leuthold
Markus Leuthold 2015 年 4 月 22 日
回答済み: Guillaume 2015 年 4 月 22 日
Assume you have the following class
classdef MyClass
methods
function fcn(~)
end
end
end
The following call of nargout
c=MyClass;
nargout(@c.fcn)
always returns -1, no matter how many output arguments the function has. Why is that?
I'm aware this already has been discussed here, but the proposed workaround
nargout('MyClass>MyClass.fcn')
is not suitable if you only know the function handle. The provided answer is already 5 years old, is there an update on this shortcoming?

回答 (1 件)

Guillaume
Guillaume 2015 年 4 月 22 日
With no guarantee that it works in all cases, this may be a workaround (not a pretty one):
function nout = nargout_for_class_fhandle(fhandle)
finfo = functions(fhandle);
fwspace = finfo.workspace{1};
wspacefields = fieldnames(fwspace);
mc = metaclass(fwspace.(wspacefields{1}));
searchnames = cellfun(@(name) sprintf('%s//.%s', wspacefields{1}, name), {mc.MethodList.Name}, 'UniformOutput', false);
midx = find(regexp(finfo.function, searchnames, 'once'));
mm = mc.MethodList(midx);
nout = numel(mm.OutputNames);
end
I've not put any error checking in there and because it attempts to find the method name in the body of the anonymous function code it could be defeated.

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by