Mlbe 12 Functions Note
Mlbe 12 Functions Note
Mlbe 12 Functions Note
MATLAB Fundamentals
12-1
Writing Functions
Outline
Creating and calling
functions
Workspace
s
Path and precedence
Debugging
Data types
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.
MATLAB Fundamentals
12-3
Writing Functions
Try
a complete data analysi
s
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.
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.
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_name(in1,in2,...)
Values are assigned to input variables when the function is called with
specific inputs.
function [] = function_name(in1,in2,...)
function function_name()
function [] = function_name
function [] = function_name()
function
function_name
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
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);
workspace from which it was called, in this case into the base workspace
variable a. Once the function is finished, its workspace is destroyed.
MATLAB Fundamentals
12-8
Writing Functions
Try
Calling Precedence
Whenever MATLAB encounters the word analysis (at the command
Chapter
3
doc import
Private function
Class method
MATLAB
Techniques
Programming
MATLAB
Techniques
Programming
MATLAB
Techniques
Programming
MATLAB
Techniques
Programming
particular reference:
>> which
analysis
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.
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
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.
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.
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.
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.
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.
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
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
See the documentation for details on the various numeric types: MATLAB
MATLAB Fundamentals
12-16
Writing Functions
Try
apples
42
exist already).
If S already exists, but is not a structure, a warning will result, because S will
% error!
% 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'
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
MATLAB Fundamentals
12-18
Writing Functions
2.
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.
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
MATLAB Fundamentals
12-20