23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

12 <strong>Programming</strong> Tips<br />

Function Arguments<br />

This section covers the following topics:<br />

• “Getting the Input and Output Arguments” on page 12-16<br />

• “Variable Numbers of Arguments” on page 12-16<br />

• “String or Numeric Arguments” on page 12-17<br />

• “Passing Arguments in a Structure” on page 12-17<br />

• “Passing Arguments in a Cell Array” on page 12-18<br />

Getting the Input and Output Arguments<br />

Use nargin and nargout to determine the number of input and output<br />

arguments in a particular function call. Use nargchk and nargoutchk to<br />

verify that your function is called with the required number of input and<br />

output arguments.<br />

function [x, y] = myplot(a, b, c, d)<br />

disp(nargchk(2, 4, nargin))<br />

disp(nargoutchk(0, 2, nargout))<br />

% Allow 2 to 4 inputs<br />

% Allow 0 to 2 outputs<br />

x = plot(a, b);<br />

if nargin == 4<br />

y = myfun(c, d);<br />

end<br />

Variable Numbers of Arguments<br />

You can call functions with fewer input and output arguments than you have<br />

specified in the function definition, but not more. If you want to call a function<br />

with a variable number of arguments, use the varargin and varargout<br />

function parameters in the function definition.<br />

This function returns the size vector and, optionally, individual dimensions:<br />

function [s, varargout] = mysize(x)<br />

nout = max(nargout, 1) - 1;<br />

s = size(x);<br />

for k = 1:nout<br />

12-16

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

Saved successfully!

Ooh no, something went wrong!