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.

Function Arguments<br />

Function Arguments<br />

When calling a function, the caller provides the function with any data it<br />

needs by passing the data in an argument list. Data that needs to be returned<br />

to the caller is passed back in a list of return values.<br />

Semantically speaking, <strong>MATLAB</strong> always passes argument data by value.<br />

(Internally, <strong>MATLAB</strong> optimizes away any unnecessary copy operations.)<br />

If you pass data to a function that then modifies this data, you will need to<br />

update your own copy of the data. You can do this by having the function<br />

return the updated value as an output argument.<br />

This section covers<br />

• “Checking the Number of Input Arguments” on page 4-33<br />

• “Passing Variable Numbers of Arguments” on page 4-35<br />

• “Parsing Inputs with inputParser” on page 4-37<br />

• “Passing Optional Arguments to Nested Functions” on page 4-48<br />

• “Returning Modified Input Arguments” on page 4-51<br />

Checking the Number of Input Arguments<br />

The nargin and nargout functions enable you to determine how many input<br />

and output arguments a function is called with. You can then use conditional<br />

statements to perform different tasks depending on the number of arguments.<br />

For example,<br />

function c = testarg1(a, b)<br />

if (nargin == 1)<br />

c = a .^ 2;<br />

elseif (nargin == 2)<br />

c = a + b;<br />

end<br />

Given a single input argument, this function squares the input value. Given<br />

two inputs, it adds them together.<br />

4-33

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

Saved successfully!

Ooh no, something went wrong!