2

I was just writing a Matlab function and wanted to copy and paste what I had to an interactive session. Some of it was nargin statements (e.g. if nargin < 1; a = 0; end;), and it turns out that nargin had the value 11005 in my workspace, without my having assigned it. Does anyone know what this is, whether it is used for anything (outside of functions) and if there is any problem with setting it to zero?

carandraug
  • 12,938
  • 1
  • 26
  • 38
Nagel
  • 2,576
  • 3
  • 22
  • 20
  • 2
    It has *likely* that value because at the global workspace scope (when used as a variable and not as function) it has no use, thus it is unassigned. *Undefined-behavior kind of stuff.* BTW, you can still use it as function (at workspace level) to have the number of parameters the signature of a certain function features. – Acorbe Nov 27 '12 at 13:38
  • 1
    From [docs](http://www.mathworks.com/help/matlab/ref/nargin.html): "`nargin` returns the number of input arguments passed in the call to the currently executing function. Use this `nargin` syntax *only in the body of a function*." – plesiv Nov 27 '12 at 13:40

1 Answers1

3

When used within a function, nargin gives the number of parameters passed to that function. Used with a string argument fn it is an in-built function, which returns the number of parameters taken by function fn. You should not call it without a parameter from the workspace:

nargin returns the number of input arguments passed in the call to the currently executing function. Use this nargin syntax only in the body of a function.

You can, but you should avoid assigning a value to nargin, since it will then loose the second semantics:

nargin('sparse')

ans =

 6

nargin = 0;
nargin('sparse')
Index exceeds matrix dimensions.
angainor
  • 11,760
  • 2
  • 36
  • 56
  • That's interesting...In the last case you are hiding the real function name behind a variable name. In principle you can do with every function. – Acorbe Nov 27 '12 at 13:49
  • @Acorbe yes, probably not very useful.. Unless you want to introduce hard to find bugs into your code ;) – angainor Nov 27 '12 at 13:53
  • @Acorbe, I actually encounter that all the time. E.g., I often have to fight hard to resist the temptation to call a variable `set` :) – Nagel Nov 27 '12 at 14:31
  • @angainor: Thanks for your reply! It explains what I need to know. (One question remains, however: What does nargin return without arguments? The total number of input arguments for all functions on your path perhaps... Or maybe it is just, as Acorbe says, "undefined-behavior kind of stuff".) – Nagel Nov 27 '12 at 14:33
  • 1
    @Nagel in my matlab it returns 0. Don't use it might mean we don't know what it returns ;) – angainor Nov 27 '12 at 14:36
  • Interesting! I now see that it returns 0 in Matlab on my MacBook too, but when I start a new Matlab session on one of my lab's servers, it returns some number in the thousands... – Nagel Nov 27 '12 at 14:51