Mlbe 12 Functions Note

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

Writing Functions

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-1

Writing Functions

Outline
Creating and calling
functions
Workspace
s
Path and precedence
Debugging
Data types

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-2

Writing Functions

Chapter Learning
Outcomes
The attendee will be able to:
Create and call a function
file.
Set the MATLAB path to ensure a code file is
visible.
Determine which file or variable is being accessed when a MATLA
command is issued.
B
Use diagnostic tools to find and correct problems in code
files.
Store, access, and manipulate data in a
structure.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-3

Writing Functions

Course Example: Electricity


Modeling
The script analysis_script.m implements

Try
a complete data analysi
s

workflow on the electricity usage data:


1. Import data from file.
2. Preprocess the data (remove
3. NaNs). Fit a polynomial to the
4. data.
5. Use the fitted model to predict the
usage at a future date. Make a plot
thefew
datalines
and of
thethe
fitted
model.
Theof
first
script
define some important
The name of the data file
variables:
The degree of the polynomial to fit to the
edict the usage
data
The future date at which to pr

2014 by MathWorks, Inc.

View and run a script that analyzes the electricity usage data.
>> edit analysis_script
>> analysis_script
These are typically the kinds of parameters that you would change before
rerunning the script.
The goal of the example in this chapter is to convert this script into a
function so that the analysi can be run with different parameters without
changing the code. s

MATLAB Fundamentals

12-4

Writing Functions

Why Use
Functions?
As the complexity of your scripts increases, you will most likely find
that
certain pieces of code are repeated in several different places. In this case,
it makes sense to package this segment of code as a separate, general
helper code that you can call with a single command. In this way
you reduce maintenance effort: if you change this block of code, you now
need change it in one place only.

2014 by MathWorks, Inc.

It is possible to call scripts from within other scripts. However, this


is
generally not recommended as all scripts share the MATLAB (base)
workspace. Hence, any change made to a variable by one script affects all
the other scripts that reference that variable. Furthermore, you need to
keep a careful inventory of your workspace so that all scripts are using
the same variable names. This undermines the purpose of keeping your
code modular so as to be more maintainable.
A better solution is to create your own functions. A function can be seen as
a
black box: code that requires certain types of inputs, performs some
action, and
some
it isvariables
running,inyou
typicallyoccupy
never see
inside
the returns
box, just
theoutputs.
output. As
The
a function
own,
separate workspace.
the actions
their

MATLAB Fundamentals

12-5

Writing Functions

Creating a
Function
Functions are created in text files with a .m extension, just like scripts.

Function files have one key syntactic difference with script files: function
files
always begin with a function declaration.
function [out1,out2,...] = function_name(in1,in2,...)

The keyword function must be the first (noncomment) code in the file.

The function declaration syntax (after the function keyword) is


identical to the syntax for calling functions in MATLAB.
For functions with a single output, the square brackets are unnecessary
(and slightly less efficient).
To avoid confusion, the file should be named function_name.m (that
is, the function name used in the declaration should match the file
name).

Try
Edit analysis_script.m to turn it into a function that accepts
a file name, a polynomial degree (scalar value), and a date as
inputs, and returns the usage predicted by the model as an output.
Solution
>> edit analysis_func

There are times when you may want to create a function that has no input
or
no output (or even both). To accommodate such situations, the following
are all valid declaration syntaxes:
function

[out1,out2,...] = function_name()

function [out1,out2,...] = function_name


function

function_name(in1,in2,...)

Values are assigned to input variables when the function is called with
specific inputs.

function [] = function_name(in1,in2,...)

Code following the function declaration describes how output variables


are
computed from input variables.

function function_name()
function [] = function_name
function [] = function_name()

function

function_name

Each declared output must be assigned a value somewhere in the code.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-6

Writing Functions

Calling a
Function
User-defined functions are called just like any other MATLAB functions.
The
calling syntax is specified in the declaration on the first line of code in
the function file.
The values of the inputs given when the function is called are assigned,
in
order, to the variables in the function declaration line:
>> [x,y] = myfunction(42,pi,0);
function [frogs,bats] = myfunction(a,b,c)
frogs = a + b;
bats = b + c;

Try
Call the analysis function.
>> enddate = datetime(2020,1,1);
>> usage2020 = analysis_func(...
'electricityUsage.xls',3,enddate)
Call it again with the same data file but different analysis parameters.
>> enddate = datetime(2015,1,1);
>> usage2020 = analysis_func(...
'electricityUsage.xls',2,enddate)

If only y is needed, however, you can tell MATLAB to ignore x by using the
tilde (~) as a placeholder:

Inside myfunction, a will have the value 42, b will have the value pi, and

>> [~,y] = myfunction(42,pi,0);

c will have the value 0.

Now y will be assigned the value pi and the value assigned to frogs
inside the function will be ignored
As always, if no return variable is specified when the function is called,
the
result is returned to the default variable ans. If the function returns more
than one output, the first will be assigned to ans (and the others ignored).
Note MATLAB always uses the function definition that is saved on disk.
Be
sure to save any changes made to a function before calling it.

Similarly, the outputs are assigned in order. In the above example, the
variable
frogs inside the function will have the value 45.1416 and bats will
have the value pi. Hence, in the base MATLAB workspace, x will be
assigned the value 45.1416 and y will be assigned the value pi.
If a function is written to return multiple outputs, it is not necessary to
return
all of the outputs. For example, if only the output x is needed, you can
call
myfunction by typing

>> x = myfunction(42,pi,0);
Now x will be assigned the value 45.1416. The value assigned to bats
inside the function (pi) will be ignored.
2014 by MathWorks, Inc.

MATLAB Fundamentals

12-7

Writing Functions

Workspace
s
Functions operate within their own function workspace, separate from the
base
workspace accessed at the prompt or from within scripts. If a function
calls another function, each maintains its own separate workspace.
The separate workspaces of functions are convenient, but also a possible
source of error.
The convenience comes with variable naming. You could, for example,
have
all of your functions accept input x and return output y. There would
never be any confusion because the values of the variables are local to the
individual function workspaces. Similarly, you may create variables within
a function safe in the knowledge that these variables are unique to that one
function. There is no need to worry about variable name conflicts among
your function files.

Try
Verify that function variables are local to the function workspace.
>> edit foo
Watch the base workspace.
>> a = 42;
>> b = foo(a);

A common source of error in function programming is to refer to a


variable
in one function workspace (or the base workspace) from another function
workspace. Because the workspaces are separated in memory, their
variables are hidden from one another. MATLAB will tell you that the
variable is not found.
Because workspaces are kept separate, MATLAB passes by value. That
is, when
you make a call such as
>> a = foo(b)
to a function with a declaration line of
function y = foo(x)
MATLAB passes the value of b into
foo.

The variable x in the foo


workspace thus takes this value, but is a separate variable to b (which resides
in the base workspace). Hence, changes to x do not affect b. Similarly, once
foo is done running, it copies the value currently in its variable y back to the

workspace from which it was called, in this case into the base workspace
variable a. Once the function is finished, its workspace is destroyed.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-8

Writing Functions
Try

Calling Precedence
Whenever MATLAB encounters the word analysis (at the command

prompt or in an executing code file), it looks for the first instance of


something called analysis from the following
list:
Location
Reference
1

Variable in the local workspace

Function from an imported package

Chapter
3
doc import

Nested function within the current


function

Local function within the same file

Private function

Class method

Class constructor in an @ folder

File in the current directory

9 File on the MATLAB path


(Items in bold are discussed in this
course.)

MATLAB
Techniques

Programming

MATLAB
Techniques

Programming

MATLAB
Techniques

Programming

MATLAB
Techniques

Programming

Determine which files are being accessed.


>> which analysis_func
>> which analysis_func -all
Observe how local variables take precedence over functions.
>> which mean -all
>> mean = 2
>> which mean
>> which mean -all
>> mean(1)
>> mean([1 5 3])
>> clear mean
>> which mean

You can use the which

particular reference:
>> which

command to see how MATLA is resolving a


B

analysis

>> which analysis -all

If there is more than one file named analysis in the directory found in

Next page
step 8 or 9, MATLAB gives precedence according to extension:
1. Built-in files (.bi extension)
2.
3. MATLAB executable (MEX) files (.mex* extension)
4.
Simulink models (.slx or .mdl extension)
5.
Encrypted MATLAB code files (.p extension)
MATLAB
code files (.m
2014
by MathWorks,
Inc. extension)

MATLAB Fundamentals

12-9

Writing Functions

The MATLAB
Path
Rather than search everywhere on your computer (and possibly your
network)
to determine if analysis is a valid command or function call,
MATLAB
has its own
search pathallof directories
where itwith
will look
for codeand
files. any
During
installation,
files supplied
MATLAB
installed
MathWorks toolboxes are placed on the search path. If you create new
MATLAB related files, you must ensure that the directories containing the
files are placed on the search path. Subdirectories must be explicitly
added, even if parent directories are on the path.
To set and edit the search path, open the Set Path dialog by clicking the
Set
Path button in the Environment section of the Home tab of the toolstrip:

search
in order

The path can also be edited programmatically using functions such as path,
addpath, rmpath, and savepath.

The order of the directories on the search path is important if you have
more
than one file with the same name (independent of the extension). When
MATLAB
for same
a file,name
only the
precedence
found.
theiswhich
Other
fileslooks
with the
are one
said with
to behighest
shadowed.
Use
function to determine which instance of a file is being
accessed.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-10

Writing Functions

Debugging
Because function workspaces are local and temporary, finding problems
with
your code can be difficult.
The MATLAB Editor has an integrated code analysis tool that provides
a
check for syntax errors as the code is being written. For example:
strings missing a delimiter (') are colored red, while closed strings turn
purple; code inside loops is indented; closing parentheses are briefly
highlighted with their opening counterpart.
A small, square box in the upper right corner of the Editor shows the
current
state of the code.
Color
Meaning
Green
Orange

There are no detectable syntax errors in the


code.

Try
View a version of analysis_func that has a bug in it. Use the Code
Analyzer messages to find potential problems.
Try to call the function. Did it work? If not, follow the error message
link to find where the problem occurred.
>> usage2020 = analysis_debug(...
'electricityUsage.xls',3,enddate)
Scripts and functions can invoke other scripts and functions. Hence, when
errors do occur, they may originate several layers deep into the progression
of
function
calls. MATLAB shows the error message from each function.
Careful review of this stack trace may reveal the source of the
error.
Error messages in MATLAB give the line number where the error
occurred.
Clicking the error message will open the appropriate file in the Editor.

There
a potential
for unexpected results
or pooriscode
performance.

Red
There are syntax errors that will prevent code
running.
Additionally,from
specific
problems within the code appear with an orange or
red
underline.
description
is shown the
whenever
the suggests
mouse is ahovered
over the
highlightedA code.
Sometimes
message
correction
or
improvement.
A green box indicates that the Code Analyzer could not detect any
syntax
errors or common problems. This does not mean, however, that the code
is necessarily free of run-time errors.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-11

Writing Functions

Using
Breakpoints
If an error message is not enough to diagnose a problem, you can activate
the
MATLAB Debugger by setting a breakpoint in the Editor. Breakpoints
are specific
lines of code
where
MATLAB
to stopopen and
hold
everything
that is,
keepyou
allwould like
function
workspaces
execution and
active
accessible.
To set a breakpoint using the Editor,
click a dash in the breakpoint column
next to the line number of an
executable line of code. The dash
turns into a red dot. The breakpoint
is
disabled (gray) if there is a syntax
error or if you have not saved to a
directory on the path. To remove the
breakpoint, click the dot.
After setting a breakpoint, run the
file.
The program pauses at the first
breakpoint.
arrow justcolumn
to the
right
of A
thegreen
breakpoint
indicates where execution is paused.
Note The line of code indicated by
the arrow has not yet been executed.
A hollow arrow indicates that control
is in another function call.

2014 by MathWorks, Inc.

Try
Set a breakpoint in analysis_debug.m near a line relevant to
the error message. Rerun the previous command at the command
line to activate debug mode.

You can use the Step and Continue


controls in the Debug section of the
Editor tab to step through the program
one line at a time (F10), or continue to
the next breakpoint (F5).

The function displayed in the Stack


field
on the toolbar at the top of the Editor
changes to reflect the current function.
The prompt changes to the debug
command prompt (K>>) to indicate that
MATLAB has entered debug mode
(or keyboard mode, hence the K in the
prompt).

MATLAB Fundamentals

12-12

Writing Functions

Examining
Values
Examine values of variables when you want to see whether a line of code
has
produced the expected result or not. If the result is as expected, continue
running or step to the next line. If not, then that line, or a previous line,
contains an error.
In debug mode, you can enter commands in the Command Window to
examine values. In the Editor, if you position your cursor near a variable,
its current value pops up as a data tip. The data tip stays in view until you
move the cursor.

2014 by MathWorks, Inc.

Try
Examine the dimensions of the variables in analysis_debug.m
while in debug mode. Locate and correct the run-time error.

In debug mode, you can choose any active workspace from the Function
Call
Stack in the Debug section of the Editor tab. The workspace variables
then appear in the Workspace browser where they can be examined in the
Variable Editor or in the Command Window.

MATLAB Fundamentals

12-13

Writing Functions

Ending Debugging
While debugging, you can change the value of a variable in the current
workspace to see if a new value produces the expected results. While the
program is paused, assign a new value to the variable in the Command
Window Workspace browser, or Array Editor, then continue running
,
or through the program. If the new value does not produce
stepping the
expected
results, the program has another
problem.
After identifying a problem, end the debugging session. You must end
a
debugging session if you want to change and save a file to correct a
problem, or if you want to run other functions in MATLAB. If you edit a
file while in debug mode, you can get unexpected results when you run the
file.

2014 by MathWorks, Inc.

Try
Find and correct all bugs in analysis_debug.m. Exit debug
mode, save the file, and clear all breakpoints.
Verify that the function is now working correctly.
>> usage2020 = analysis_debug(...
'electricityUsage.xls',3,enddate)
To end debugging, click the Quit Debugging button. After quitting
debugging, the pause arrows in the Editor display no longer appear, and
the normal prompt >> reappears in the Command Window. You can no
longer access the call stack.
After you think you have identified and corrected a problem, you can
disable
breakpoints so that the program ignores them, or you can remove them
entirely. Clicking a breakpoint dot clears it. Right-clicking a breakpoint
dot shows a context menu that will allow you to disable the breakpoint (an
X will appear through the dot) or clear it.

MATLAB Fundamentals

12-14

Writing Functions

Course Example:
Adding Model
Parameters
The function analysis_inputs.m implements a more complicated

analysis of the electricity usage data, including averaging consecutive


blocks
of months before fitting a polynomial to a subset of the averaged data.
The function returns the predicted usage, and also optionally creates a
plot.
This more complicated algorithm requires more parameters, which means
that
function
inputs:
thisThe
name takes
of thesix
data
file
The degree of the polynomial to fit to the
data The future date at which to predict the
usage The number of months over which to
average
The number of months to use as the data
subset to which the model is fitted
A flag that specifies whether or not to make the plot

2014 by MathWorks, Inc.

Try
Call the analysis function with six inputs.
>> enddate = datetime(2015,1,1);
>> usage2020 = analysis_inputs(...
'electricityUsage.xls',3,enddate,...
12,120,true)
A function call with six inputs is not easy to interpret. Furthermore, as part
of
a larger application, some or all of these inputs may be required as inputs
to other functions.
In situations like this, it is helpful to have the function accept an input that
is a
collection of individual parameters. This is commonly achieved with
structures (see page 12-17), which allow you to combine data of diverse
types and sizes. Furthermore, structures use named indexing, which
makes interpretation of the data organization easier.
Several MATLAB functions that implement algorithms with many
options
take
thisby
approach.
The
options are specified in a structure, which is
created
a separate
function.
typically

MATLAB Fundamentals

12-15

Writing Functions

MATLAB Data Types


The graphic below shows the fundamental data types
in
available
A
variable any data type is an array with a characteristic organization
MATLAB.
of
of
data.
Array sizes range from 0-by-0 (empty) to the maximum size your computer

memory allows. MATLAB puts no limits on size.

See the documentation for details on the various numeric types: MATLAB

Language Fundamentals Data Types Numeric Types. In


particular, note that there are particular rules for how arithmetic is
implemented when using nondouble variables. These rules are
summarized on page A-15 in Appendix A (MATLAB Reference).
You can convert between data types: MATLAB Language
Fundamentals Data Types Data Type Conversion. Conversion
functions are summarized on page A-17 in Appendix A (MATLA
Reference).
B

You can create additional data types as user-defined


classes.
Function handles and categorical arrays are not discussed this course.
on as a
in
Function
handles
provide
a way totostore
to repres
a functivariable.
Categorical
arrays
intended
storea reference
text labels
nting a finite
e
are
number of categories.

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-16

Writing Functions
Try

Combining Heterogeneous Data


with
Structures
You can use structure arrays to assemble data of dissimilar types and
sizes
into one variable. Structure arrays use named referencing like tables, but
there is no requirement that the data conform to a tabular arrangement.
Data in structures arrays is referenced by named fields. The
command
S

>> S.apples = 42;

apples

Create a single structure containing necessary model information.


>> mymodel = struct(...
'datafile','electricityUsage.xls',...
'polydegree',3,'predictdate',enddate,...
'monthavg',12,'nummonthmodel',120,...
'makeplot',true)
Pass a single structure argument to a function that analyzes
electricity usage data.
>> edit analysis_struct
>> usage2020 = analysis_struct(mymodel)

42

creates a structure S with a field


called apples, which takes the value of 42.
If S is already a structure, the field apples will be added to it (if it doesnt

exist already).
If S already exists, but is not a structure, a warning will result, because S will

As usual, referencing a nonexistent fieldname will result in an error, but


assigning to a nonexistent fieldname will cause that field to be
created:
>> x = S.oranges;

% error!

>> S.oranges = [1,2,3];

% OK

be converted to a structure.
Each field of a structure can contain data of different sizes and
types:
>> S.bananas

= 'green';

S
apples

42

bananas

'green'

2014 by MathWorks, Inc.

S
apples

42

bananas

'green'

oranges

[1,2,3]

MATLAB Fundamentals

12-17

Writing Functions

Summary
Creating and calling
functions
Workspace
s
Path and precedence
Debugging
Data types

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-18

Writing Functions

Test Your Knowledge

2.

Which of the following is a valid function


declaration?
A. function [x,y] = foo(a,b)
B.
function foo(a,b) = [x,y]
C.
[x,y] = function foo(a,b)
D.
[x,y] = foo(a,b)

3.

(Select all that apply) Which of the following are valid calls to a
function
with the declaration line function
[x,y] = foo(a,b)?

Name:

1.

Suppose the workspace contains a vector x and the function foo creates
a scalar variable also called x. What will happen to the vector x if you
issue the command >> z = foo(7)?
A. It will change to the scalar value defined in foo.

B.

dimensions
Nothing, because the two variables are of
different
C. Nothing, because the vector x is not passed
as an argument to
(i.e., a vector cannot be changed to a scalar).
D. foo.
Nothing, because foo maintains its own workspace, so there is no
name conflict.

2014 by MathWorks, Inc.

A.
B.
C.
D.
E.

[x,y] = foo(a)

x = foo(a,b)
[x,y]

= foo[a,b]

(x,y) = foo(a)
[x,y] = foo(a,b)

MATLAB Fundamentals

12-19

Writing Functions

2014 by MathWorks, Inc.

MATLAB Fundamentals

12-20

You might also like