| Programming and Data Types | ![]() |
Checking the Number of Function Arguments
The nargin and nargout functions let you determine how many input and output arguments a function is called with. You can then use conditional statements to perform different 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 two inputs, it adds them together.
Here's a more advanced example that finds the first token in a character string. A token is a set of characters delimited by whitespace or some other character. Given one input, the function assumes a default delimiter of whitespace; given two, it lets you specify another delimiter if desired. It also allows for two possible output argument lists.
function [token,remainder] = strtok(string,delimiters)
% Function requires at least one input argument
if nargin < 1
error('Not enough input arguments.');
end
token = []; remainder = [];
len = length(string);
if len == 0
return
end
% If one input, use white space delimiter
if (nargin == 1)
delimiters = [9:13 32]; % White space characters
end
i = 1;
% Determine where non-delimiter characters begin
while (any(string(i) == delimiters))
i = i + 1;
if (i > len), return, end
end
% Find where token ends
start = i;
while (~any(string(i) == delimiters))
i = i + 1;
if (i > len), break, end
end
finish = i - 1;
token = string(start:finish);
% For two output arguments, count characters after
% first delimiter (remainder)
if (nargout == 2)
remainder = string(finish + 1:end);
end
The strtok function is a MATLAB M-file in the strfun directory.
| How Functions Work | Passing Variable Numbers of Arguments | ![]() |