23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4 M-File <strong>Programming</strong><br />

Using nargin and nargout<br />

When nargin or nargout appears in a nested function, it refers to the number<br />

of inputs or outputs passed to that particular function, regardless of whether<br />

ornotitisnested.<br />

In the example shown above, nargin in function A is the number of inputs<br />

passed to A, andnargin in function C is the number of inputs passed to C. Ifa<br />

nested function needs the value of nargin or nargout from an outer function,<br />

youcanpassthisvalueinasaseparateargument,asdoneinfunctionB.<br />

Example of Passing Optional Arguments to Nested Functions<br />

This example references the primary function’s varargin cell array from<br />

each of two nested functions. (Because the workspace of an outer function is<br />

shared with all functions nested within it, there is no need to pass varargin<br />

to the nested functions.)<br />

Both nested functions make use of the nargin value that applies to the<br />

primary function. Calling nargin from the nested function would return the<br />

number of inputs passed to that nested function, and not those that had been<br />

passed to the primary. For this reason, the primary function must pass its<br />

nargin value to the nested functions.<br />

function meters = convert2meters(miles, varargin)<br />

% Converts MILES (plus optional FEET and INCHES input)<br />

% values to METERS.<br />

if nargin < 1 || nargin > 3<br />

error('1 to 3 input arguments are required');<br />

end<br />

function feet = convert2Feet(argsIn)<br />

% Nested function that converts miles to feet and adds in<br />

% optional FEET argument.<br />

feet = miles .* 5280;<br />

if argsIn >= 2<br />

feet = feet + varargin{1};<br />

end<br />

4-50

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!