1

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?

1 Answers1

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