Matabian equivalent of Python "None"

Is there a keyword in matlab that is roughly equivalent to None in python?

I am trying to use it to indicate an optional function argument. I am translating the following Python code

 def f(x,y=None): if y == None: return g(x) else: return h(x,y) 

in matlab

 function rtrn = f(x,y) if y == []: rtrn = g(x); else rtrn = h(x,y); end; end 

As you can see now, I use [] as None . Is there a better way to do this?

+6
python matlab
Nov 15 '09 at 13:23
source share
3 answers

in your particular case. you can use nargin to determine how many input arguments are provided here when the function is called.

from MATLAB Documentation :

The nargin and nargout functions allow you to determine how much input and output arguments function c. You can then use conditional statements to perform various tasks depending on the number of arguments. For example,

 function c = testarg1(a, b) if (nargin == 1) c = a .^ 2; elseif (nargin == 2) c = a + b; end 

Given a single input argument, this function squares the input value. Given the two inputs, he adds them together.

+10
Nov 15 '09 at 13:46
source share

NaN , although not equivalent, often serves a similar purpose.

+7
Nov 15 '09 at 13:33
source share

nargin is by far the easiest way to do this. It is also generally recommended to check the number of input arguments using nargchk :

 function e = testFunc(a,b,c,d) error( nargchk(2, 4, nargin, 'struct') ); % set default values if nargin<4, d = 0; end if nargin<3, c = 0; end % .. c = a*b + c*d; end 

... which acts as a way of ensuring the correct number of arguments. In this case, a minimum of two arguments is required, a maximum of four.

If nargchk does not detect an error, execution resumes normally, otherwise an error is generated. For example, a call to testFunc(1) generates:

 Not enough input arguments. 

UPDATE: a new function was introduced in R2011b narginchk , which replaces the use of the deprecated nargchk + error above:

 narginchk(2,4); 

You can use functions like: exist and isempty to check if a variable exists and is empty:

 if ~exist('c','var') || isempty(c) c = 10; end 

which allows you to call your function, such as: testFunc(1,2,[],4) it to use the default value for c , but still giving a value for d

You can also use varargin to accept a variable number of arguments.

Finally, a powerful way to parse and validate named inputs is to use inputParser

To see examples and other alternatives for passing arguments and set defaults, check out this post and its comments.

+7
Nov 15 '09 at 18:00
source share



All Articles