For example, I have a function that will run with two inputs. However, if only one input is entered, I want Matlab to run a different line of code (using an if-else statement). How can I do that without Matlab automatically returning an error when there are not enough inputs?
Asked
Active
Viewed 83 times
1
-
2Check [`varargin`](http://es.mathworks.com/help/matlab/ref/varargin.html) – Luis Mendo Oct 20 '15 at 22:41
1 Answers
0
You have many possibilities. You can use varargin, it will pass a cell array with all arguments to your function:
function f1(varargin)
switch numel(varargin)
case 1
disp(varargin{1})
case 2
disp(varargin{1})
disp(varargin{2})
end
end
You could also check the number of input arguments using nargin
and not use the second input argument if it not exists.
function f2(x,y)
switch nargin
case 1
disp(x)
case 2
disp(x)
disp(y)
end
end
A third possibility is to check if y
exists. It will not exist if you don't pass an argument:
function f3(x,y)
if not(exist('y','var'))
disp(x)
else
disp(x)
disp(y)
end
end

Daniel
- 36,610
- 3
- 36
- 69