Find Number of Function Arguments - MATLAB & Simulink (original) (raw)

Main Content

This example shows how to determine how many input or output arguments your function receives using nargin and nargout.

Input Arguments

Create a function in a file named addme.m that accepts up to two inputs. Identify the number of inputs with nargin.

function c = addme(a,b)

switch nargin case 2 c = a + b; case 1 c = a + a; otherwise c = 0; end

Call addme with one, two, or zero input arguments.

Output Arguments

Create a new function in a file named addme2.m that can return one or two outputs (a result and its absolute value). Identify the number of requested outputs with nargout.

function [result,absResult] = addme2(a,b)

switch nargin case 2 result = a + b; case 1 result = a + a; otherwise result = 0; end

if nargout > 1 absResult = abs(result); end

Call addme2 with one or two output arguments.

[value,absValue] = addme2(11,-22)

value = -11

absValue = 11

Functions return outputs in the order they are declared in the function definition.

See Also

nargin | narginchk | nargout | nargoutchk