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.

Subfunctions<br />

Subfunctions<br />

• “Calling Subfunctions” on page 5-34<br />

• “Accessing Help for a Subfunction” on page 5-34<br />

M-files can contain code for more than one function. Additional functions<br />

within the file are called subfunctions, andtheseareonlyvisibletothe<br />

primary function or to other subfunctions in the same file.<br />

Each subfunction begins with its own function definition line. The functions<br />

immediately follow each other. The various subfunctions can occur in any<br />

order, as long as the primary function appears first:<br />

function [avg, med] = newstats(u) % Primary function<br />

% NEWSTATS Find mean and median with internal functions.<br />

n = length(u);<br />

avg = mean(u, n);<br />

med = median(u, n);<br />

function a = mean(v, n)<br />

% Calculate average.<br />

a = sum(v)/n;<br />

function m = median(v, n)<br />

% Calculate median.<br />

w = sort(v);<br />

if rem(n, 2) == 1<br />

m = w((n+1) / 2);<br />

else<br />

m = (w(n/2) + w(n/2+1)) / 2;<br />

end<br />

% Subfunction<br />

% Subfunction<br />

The subfunctions mean and median calculate the average and median of the<br />

input list. The primary function newstats determines the length of the list<br />

and calls the subfunctions, passing to them the list length n.<br />

Subfunctions cannot access variables used by other subfunctions, even within<br />

thesameM-file,orvariablesusedbythe primary function of that M-file,<br />

5-33

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

Saved successfully!

Ooh no, something went wrong!