5.1: User-Defined Functions
- Page ID
- 14936
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Up to now, the M-files that you have created are called “script” files. Now we use the editor to create function M-files. Why would you want to do this? Well, Matlab has many built-in functions, but you may need to create your own to solve a specialized problem.
Lets look at how a function is put together. In the command window, if you were to type
>> help sin
you would get
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also asin, sind
Reference page in Help browser
doc sin
In reading this, you can see the purpose of the function, the correct usage of the function and references to additional related functions. When you create your own functions, you will also need to create similar information.
Here’s how to create a function in Matlab. In the Editor window, follow these steps:
1) On the first line(s) put comments that describe the function and, most importantly, a usage statement or HOW THE USER ENTERS THE FUNCTION!!!
2) On the next line, put the word function followed by:
- In [ ], put the variable(s) (separated by commas) for the function output(s).
- The = symbol
- Your function name
- In ( ), put the variable(s) (separated by commas) for the function input(s).
3) On the following lines, put the calculations that define the output variables based on the input variables.
Easy right??
A couple of comments before we get to some examples.
Key Idea 1
Function Tips:
- If you have exactly one output the aren't needed (see step 2a)
- Functions must follow the same naming conventions as for variables (do a Google search)
Let’s look at an example of a function that computes the area of a triangle.
Example 5.1.1: Area of a triangle function
Here is the syntax that you would type into an editor window:
% Usage: Area=TriangleArea(base,height)
% Inputs: base and height are scalars
% Output: Area - area of a triangle
function Area=TriangleArea(base,height)
Area = 0.5*base.*height;
Now save this file as TriangleArea.m. Your file name must exactly match the name of the function (except for the .m part) or else the function will not run.
In order to execute any function, you cannot use the Matlab run button. You must run the function from the command window or another M-file since you need to provide the input(s). First, check that you have provided enough comments about how to use the function:
>> help TriangleArea
which will give your description of how to use the function. Now, run the
function with:
>> A = TriangleArea(3,4)
A =
6
Note
In the program TriangleArea.m the variables Area, base and height are called local variables. That means they are only used in this specific program. They don’t appear outside the function (or in the Workspace).
Example 5.1.2: Rectangle function
Here is the syntax that you would type into an editor window:
% Usage: [Area,Perimeter]=Rectangle(base,height)
% Inputs: base and height are vectors of the same length
% Outputs:
% Area - area of a rectangle
% Perimeter perimeter of a rectangle
function [Area,Perimeter]=Rectangle(base,height)
Area = base.*height;
Perimeter = 2*(base+height);
Now save this file as Rectangle.m Again, make sure the usage comments are correct:
>> help Rectangle
to see your helpful comments. Now run the function:
>> [A,P] = Rectangle(3,4)
A =
12
P =
14
Here again we are reminded of the fact that Area and Perimeter are local to the function, so when we run the function, we can call the outputs by different names. When we run the function we use the shorter A and P to store the areas and perimeters.
What happens if you try to run the function without output variables? Try
>> Rectangle(3,4)
ans =
12
You only get the value that would have been assigned to the first output variable (here it’s the area). Since the calculations are just as they would be for matrices, we can try:
>> base = 1:4; height = [3 6 10 12];
and run the function:
>> [A,P] = Rectangle(base,height)
A =
3 12 30 48
P =
8 16 26 32
which gives us the areas and perimeters of the rectangles of the corresponding bases and heights.
Here are a few commands of interest:
nargin('TriangleArea') (number of inputs)
nargout('TriangleArea') (number of outputs)
nargin('mesh') (variable number of inputs)
type('TriangleArea') (returns code of M file)
One more example:
type('sin')
gives an output of ‘sin’ is a built-in function, which indicates that this last one is a built-in function whose code is not accessible.