How can I use NARGIN/NARGOUT to determine the number of input/output arguments of an object method?

조회 수: 50(최근 30일)
I am trying to determine the number of input/output arguments of an object's method. When the name of any object method is passed to NARGIN/NARGOUT, the returned value is always -1 regardless of the number of inputs/outputs specified in the method signature.
The following syntax returns -1 for any MethodName:

채택된 답변

MathWorks Support Team
MathWorks Support Team 2010년 9월 20일
The ability to call NARGIN/NARGOUT directly on object methods is not available in MATLAB. As a workaround, specify the class and method names explicitly using the following syntax:

추가 답변(3개)

Eric Salemi
Eric Salemi 2018년 7월 12일
편집: Eric Salemi 2018년 7월 12일
I suggest you use the meta information provided by the MCOS class system:
>> class = ?containers.Map;
>> method = class.MethodList({mclass.MethodList.Name} == "subsref");
>> method.InputNames
ans =
2×1 cell array
>> method.OutputNames
ans =
It is reliable in most cases except when your class definition uses the old-style @ folder or if you query a non-MCOS class such as a Java class or such. On the side note, the accepted answer will not work for a qualified class such as above, which just shows that the NARGIN/NARGOUT functions are function-oriented are have not been adapted for the MCOS class system.
  댓글 수: 2
Gunter Nitzsche
Gunter Nitzsche 2022년 8월 3일
I really like this appraoch. Surprising for me was that you really have to use the double quotes around "subref" as otherwise you get an error Undefined operator '==' for input arguments of type 'cell'.

댓글을 달려면 로그인하십시오.

Markus Leuthold
Markus Leuthold 2015년 4월 16일
It's almost five years later and this bug still exists. Any news from Mathworks on how to handle this situation in 2015?
Class C
classdef C < handle
function r=fcn1(~)
r='run fcn1';
function fcn2(~)
disp('run fcn2');
function run
function run(f)
switch nargout(f)
case 0
case 1
case -1
What I expect from the following code
>> c=C;
>> run(@c.fcn1)
run fcn1
>> run(@c.fcn2)
run fcn2
Instead I get
>> c=C;
>> run(@c.fcn1)
>> run(@c.fcn2)
How do you recommend to workaround in case where you want to know nargout from a function handle AND evaluate a function handle?

Christopher Hummersone
Christopher Hummersone 2015년 9월 18일
An indirect solution is to test for the existence of a particular variable:
This works for input variables; I haven't tested it for output variables.
  댓글 수: 1
Madhav Rajan
Madhav Rajan 2016년 2월 2일
Although it helps, with exist you will need to the know the names of the variables that you want to track. NARGIN/NARGOUT makes it easier since you do not need any book keeping.

댓글을 달려면 로그인하십시오.




Community Treasure Hunt

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

Start Hunting!

Translated by