2

I have the following scenario. In myClass.m I have defined

classdef myClass
    ...
    methods
        function y = foo(this, x)
            ...
        end
    end
end

Then I execute

obj = myClass();
nargin(@obj.foo)

and get as a result -1 while I would expect 1. The function nonetheless accepts only one argument. I actually want to pass the handle to another function (in which I don't have access) which checks the number of arguments and I want the check nargin(f)==1 to succeed. Is there a way to do that?

PS I know that if I define the method as static I will get the correct result by calling nargin(@(x)Test.foo) but the method accesses class variables.

kon psych
  • 626
  • 1
  • 11
  • 26
  • Why do you encounter a minus sign? "The minus sign indicates that the last input argument is varargin. The mynewplot function can accept an indeterminate number of additional input arguments." - https://ch.mathworks.com/help/matlab/ref/nargin.html – strpeter Dec 08 '20 at 11:10

2 Answers2

3

Even though this question got answered and accepted, I think it is worth to show a working approach, which works even without creating an instance of the class. Reference to metaclass: https://ch.mathworks.com/help/matlab/ref/metaclass.html

metaClass = ?myClass
numArgIn = zeros(length(metaClass.MethodList), 1);
names = strings(length(metaClass.MethodList), 1);
for i=1:length(metaClass.MethodList)
    names(i) = string(metaClass.MethodList(i).Name);
    numArgIn(i) = numel(metaClass.MethodList(i).InputNames);
end
disp(numArgIn(names=="foo"))

When you create a folder with the class and some modules, you can use the following one-liner notation:

nargin('@myClass/foo.m')

In the latter example, the file ending can be removed without effect.

strpeter
  • 2,562
  • 3
  • 27
  • 48
0

I can no longer verify the validity of this answer. See more recent answer(s) and comments.

Original answer

I fixed the problem by defining my own wrapper something like

function y = mywrapper(f, x)
%MYWRAPPER nargin(@(x)mywrapper(f, x)) is 1 as it should be
y = f(x);

end

I realised that nargin(@(x)@obj.foo), also does what I wanted

kon psych
  • 626
  • 1
  • 11
  • 26
  • 1
    You can also run `nargin(@(x,y,z)@obj.foo)` but it gives a "wrong" return value of 3. Why is this so? Because MATLAB analyzes the function handle and not the function behind. So your solution does not really work as expected. – strpeter Dec 08 '20 at 10:51
  • `nargin(@(x)...)` always returns 1, no matter what legal syntax you put where the ... are. This is because you are returning the number of arguments to the anonymous function, which you defined to have 1 input argument. – Cris Luengo Dec 08 '20 at 15:28
  • You must be both right. If I still had Matlab I would try to update the answer. At least there is a newer answer now. – kon psych Dec 12 '20 at 00:02