5.10: Functions with variable numbers of inputs or outputs
- Page ID
By Carey A. Smith
Many built-in MATLAB/Octave functions can be used with either a variable number of inputs or a variable number of outputs.
For example the max() function can be used in the following ways:
v = [ 0, 2, -2, 3, 1]
w = [-3, 3, 0, 1, 11]
v_max = max(v) % This returns the maximum value of the vector.
[v_max, idx_max] = max(v) % This returns both the maximum value of the vector and the index of this maximum value.
vw_max = max(v, w) % This returns a vector of the maximum corresponding values of the 2 vectors.
In order to see how MATLAB functions do this, we can look at the code for the peaks() function. This is a built-in example that creates a 3D plot.
Try these example to see what happens.
% 1a. No inputs, no outputspeaks; This creates a 3D plot on a 49x49 grid of x and y points. It also displays the algebraic function that creates the z values.
% 1b. No inputs, 3 outputs
[X,Y,Z] = peaks; % Outputs the 3D data, but does not create the plot.
% 2a. 1 input, no outputs
peaks(17); % Creates a 3D plot on a 17x17 grid of x and y points.
% 2b. 1 input, 3 outputs
[X,Y,Z] = peaks(17); % Outputs the 3D data, but does not create the plot
% 2a. Input 1 vector of axis data values
V = -2: 0.2: 1;
peaks(V); % Creates a 3D plot with x & y axes = V
% 3a. Input a pair of x and y coordinates
Z = peaks(1,2) % Computes the function at the point (X,Y). It does not create a plot.
In the command window, highlight the word peaks, right-click, and open the selection (file). You do not need to understand all the logic here. The important items are the following:
Line of 43: if nargin == 0
nargin is a MATLAB created variable that equals the number of variables input to the function when it was called.
Line 60: if nargout > 1
nargout is a MATLAB created variable that equals the number of variables in the output list when the function was called.
The peaks.m code then uses logic to determine what to compute and plot.
Learning to use of nargin and nargout in your functions is beyond this textbook. All you need to understand is many MATLAB/Octave functions use these varaibles to allow them to be called in multiple ways.
Add example text here.