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.

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

function [vout1 vout2 ... varargout] = myfun(vin1, vin2, ...)<br />

The code within the function builds the varargout cell array. The content and<br />

order of elements in the cell array determines how <strong>MATLAB</strong> assigns optional<br />

return values to output variables in the function call.<br />

Inthecasewherevarargout is the only variable shown to the left of the<br />

equal sign in the function definition line, <strong>MATLAB</strong> assigns varargout{1} to<br />

the first output variable, varargout{2} tothesecond,andsoon.Ifthereare<br />

other outputs declared in the function definition line, then <strong>MATLAB</strong> assigns<br />

those outputs to the leftmost output variables in the call statement, and then<br />

assigns outputs taken from the varargout array to the remaining output<br />

variables in the order just described.<br />

This function builds the varargout array using descending rows of a 5-by-5<br />

matrix. The function is capable of returning up to six outputs:<br />

function varargout = byRow(a)<br />

varargout{1} = ' With VARARGOUT constructed by row ...';<br />

for k = 1:5<br />

row = 5 - (k-1);<br />

% Reverse row order<br />

varargout{k+1} = a(row,:);<br />

end<br />

Call the function, assigning outputs to four variables. <strong>MATLAB</strong> returns<br />

varargout{1:4}, with rows of the matrix in varargout{2:4} and in the order<br />

in which they were stored by the function:<br />

[text r1 r2 r3] = byRow(magic(5))<br />

text =<br />

With VARARGOUT constructed by row ...<br />

r1 =<br />

11 18 25 2 9<br />

r2 =<br />

10 12 19 21 3<br />

r3 =<br />

4 6 13 20 22<br />

A similar function builds the varargout array using diagonals of a 5-by-5<br />

matrix:<br />

4-66

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

Saved successfully!

Ooh no, something went wrong!