31 December 2009 0 Comments

Matlab Quick Reference: Functions

Welcome to Stone Studio!

Functions

Syntax

1
2
3
4
5
function y = average(x)
% AVERAGE Mean of vector elements.
% only first comment line is printed when you type “lookfor average”
% the other lines print when you type “help average”
y = sum(x)/length(x); % Actual computation
1
function [Xout,Yout] = myFunc(x)

Number Of Arguments

nargin: number of input arguments nargout: number of output arguments

Number of Input Arguments

1
function testvar(x1, x2, varargin)

Varargin is a cell array. In the function body, access its cell values like this:

1
varargin{i}(k)

Number of Out Arguments

1
function [varargout] = testvar2(arrayin)

Varargout is a cell array. Assign the cell values like this:

1
varargout{i} = arrayin(k,:);

Anonymous Functions

Does not require an M-file (perfect for defining functions in the command line)

1
f = @(arglist) expression

Example:

1
sqr = @(x) x.^2;