Download - Mlbe 12 Functions Note
-
7/26/2019 Mlbe 12 Functions Note
1/20
Writing Functions
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
-
7/26/2019 Mlbe 12 Functions Note
2/20
Writing Functions
Outline
Creating and calling
functions
Workspace
s
Path and precedence
Debugging
Data types
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
-
7/26/2019 Mlbe 12 Functions Note
3/20
Writing Functions
Chapter Learning
OutcomesThe attendee will be able to:
Create and call a function
file.
Set the MATLA!
path to ensure a code file is"isible.
Deter#ine $hich file or "ariable is being accessed $hen aco##and is issued.
MATLA
%se diagnostic tools to find and correct proble#s in code
files.
Store& access& and #anipulate data in a
structure.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
-
7/26/2019 Mlbe 12 Functions Note
4/20
edict the usage
Writing Functions
Course Example: Electricity
Modeling
The script analysis_script.m i#ple#ents
$orkflo$ on the electricity usage data'
a co#plete data analysi
s
(.).
*.+.
,.
-#port data fro# file.Preprocess the data re#o"e
NaNs/. 0it a polyno#ial to thedata.
%se the fitted #odel to predict the
usage at a future date. Make a plot
of the data and the fitted #odel.
These are typically the kinds of para#eters that you $ould change befor
re1running the script.
The goal of the e2a#ple in this chapter is to con"ert this script into
function so that thechanging the code.
analysi
s
can be run $ith different para#eters $ithoThe first fe$ lines of the script define so#e i#portant
"ariables'%%
%
The na#e of the data fileThe degree of the polyno#ial to fit to thedata
The future date at $hich to pr
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
Try
3ie$ and run a script that analy4es the electricity usage data.
>> edit analysis_script
>> analysis_script
-
7/26/2019 Mlbe 12 Functions Note
5/20
Writing Functions
Why Use
Functions
-t is possible to call scripts fro# $ithin other scripts. 5o$e"er& t
is
generally not reco##ended as all scripts share the MATLA ba
$orkspace. 5ence& any change #ade to a "ariable by one script affects
the other scripts that reference that "ariable. 0urther#ore& you need
keep a careful in"entory of your $orkspace so that all scripts are us
the sa#e "ariable na#es. This under#ines the purpose of keeping yo
code #odular so as to be #ore #aintainable.
As the co#ple2ity of your scripts increases& you $ill #ost likely find
that
certain pieces of code are repeated in se"eral different places. -n this case&
it #akes sense to package this seg#ent of code as a separate& general
6helper7 code that you can call $ith a single co##and. -n this $ayyou reduce #aintenance effort' if you change this block of code& you no$
need change it in one place only.
A better solution is to create your o$n functions. A function can be seen
a
6black bo27' code that re8uires certain types of inputs& perfor#s so#e
action& and returns so#e outputs. As it is running& you typically ne"er se
the actions
6inside the bo2&7 9ust the output.o$n& separate $orkspace.
The "ariables in a function occupy
their
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
W iti F ti
-
7/26/2019 Mlbe 12 Functions Note
6/20
Writing Functions
Creating a
Function
0unctions are created in te2t files $ith a .m e2tension& 9ust like scripts.
0unction files ha"e one key syntactic difference $ith script files' function
filesal$ays begin $ith afunction declaration.
function [out1,out2,...] = function_name(in1,in2,...)
%
%The key$ord function #ust be the first nonco##ent/ code in the file.
The function declaration synta2 after the function key$ord/ is
identical to the synta2 for calling functions in MATLA.
There are ti#es $hen you #ay $ant to create a function that has no inpu
or
no output or e"en both/. To acco##odate such situations& the follo$ing
are all "alid declaration synta2es'% 0or functions $ith a single output& the s8uare brackets
and slightly less efficient/.are unnecessary
function
function
[out1,out2,...] = function_name()
[out1,out2,...] = function_name%
To a"oid confusion& the file should be na#ed function_name.m that
is& the function na#e used in the declaration should #atch the file
na#e/.
3alues are assigned to input "ariables $hen the function is called $ith
specific inputs.
Code follo$ing the function declaration describes ho$ output "ariablesare
co#puted fro# input "ariables.
:ach declared output #ust be assigned a "alue so#e$here in the code.
function
function
function_name(in1,in2,...)
[] = function_name(in1,in2,...)
%
%function
function
function
function
function_name
function_name()
[] = function_name
[] = function_name()
%
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
Try
:dit analysis_script.m to turn it into a function that accepts
a file na#e& a polyno#ial degree scalar "alue/& and a date as
inputs& and returns the usage predicted by the #odel as an output.
Solution
>> edit analysis_func
W iti F ti
-
7/26/2019 Mlbe 12 Functions Note
7/20
Writing Functions
Calling a
Function%ser1defined functions are called 9ust like any other MATLA functions.
The
calling synta2 is specified in the declaration on the first line of code in
the function file.
The "alues of the inputs gi"en $hen the function is called are assigned&inorder& to the "ariables in the function declaration line'
>> [x,y] = myfunction(42,pi,0);
-f only y is needed& ho$e"er& you can tell MATLA to ignore x by using the
tilde ~/ as a placeholder'
>> [~,y] = myfunction(42,pi,0);
;o$ y $ill be assigned the "alue pi and the "alue assigned to fros
inside the function $ill be ignored
-nside myfunction& a $ill ha"e the "alue +)& ! $ill ha"e the "alue pi& and
c $ill ha"e the "alue > x = myfunction(42,pi,0);
;o$ x $ill be assigned the "alue +,.(+(=. The "alue assigned to !ats
inside the function pi/ $ill be ignored.
!ote MATLA al$ays uses the function definition that is sa"ed on dis
esure to sa"e any changes #ade to a function before calling it.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
function [frogs,bats] = myfunction(a,b,c)
frogs = a + b;bats = b + c;
Try
Call the analysis function.
>> enddate = datetime(2020,,);
>> usage2020 = analysis_func(!!!
"electricity#sage!$ls",%,enddate)
Call it again $ith the sa#e data file but different analysis para#eters.>> enddate = datetime(20&,,);>> usage2020 = analysis_func(!!!
"electricity#sage!$ls",2,enddate)
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
8/20
Writing Functions
Wor"space
s0unctions operate $ithin their o$n function workspace& separate fro# the
base
workspace accessed at the pro#pt or fro# $ithin scripts. -f a function
calls another function& each #aintains its o$n separate $orkspace.
The separate $orkspaces of functions are con"enient& but also a possiblesource of error.
The con"enience co#es $ith "ariable na#ing. >ou could& for e2a#ple&
ha"e
all of your functions accept input x and return output y. There $ould
ne"er be any confusion because the "alues of the "ariables are local to the
indi"idual function $orkspaces. Si#ilarly& you #ay create "ariables $ithin
a function safe in the kno$ledge that these "ariables are uni8ue to that one
function. There is no need to $orry about "ariable na#e conflicts a#ong
your function files.
A co##on source of error in function progra##ing is to refer to
"ariable
in one function $orkspace or the base $orkspace/ fro# another functi
$orkspace. ecause the $orkspaces are separated in #e#ory& th
"ariables are hidden fro# one another. MATLA $ill tell you that
"ariable is not found.
ecause $orkspaces are kept separate& MATLApasses by value. Thais& $henyou #ake a call such as
>> a = foo(!)to a function $ith a declaration line of
function y = foo(x)
MATLA passes the value of ! intofoo.
The "ariable x in the foo
$orkspace thus takes this "alue& but is a separate "ariable to ! $hich resides
in the base $orkspace/. 5ence& changes to x do not affect !. Si#ilarly& once
foo is done running& it copies the value currently in its "ariable y back to the
$orkspace fro# $hich it $as called& in this case into the base $orkspa"ariable a. ?nce the function is finished& its $orkspace is destroyed.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
Try
3erify that function "ariables are local to the function $orkspace.
>> edit foo
Watch the base $orkspace.
>> a = '2;
>> b = foo(a);
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
9/20
Writing Functions
Calling #recedence
Whene"er MATLA encounters the $ord analysis at the co##andpro#pt or in an e2ecuting code file/& it looks forso#ething called analysis fro# the follo$inglist'
the first instance of
function
>ou can use the "#ic#
particular reference'
co##and to see ho$ MATLA
is resol"ing
>>
>>
"#ic#
"#ic#
analysis
analysis $all
-te#s in bold are discussed in this
course./
-f there is #ore than one file na#ed analysis in the directory found in
step @ or & MATLA gi"es precedence according to e2tension'(.).
*.
+.
,.
uilt1in files .!i e2tension/
MATLA e2ecutable M:B/ files .m%x& e2tension/
Si#ulink! #odels .slx or .m'l e2tension/
:ncrypted MATLA code files .p e2tension/
MATLA code files .m e2tension/ 2014 by MathWorks, Inc. MATLAB Funda!nta"s 12
Location $e%erence
& 'ariable in the local wor"space
) 0unction fro# an i#ported package
*;ested function $ithin the current
+ Local function $ithin the sa#e file
, Pri"ate function
= Class #ethod
Class constructor in an folder
( File in the current directory
) File on the M*TL*+ path
Chapter
,
'oc import
MATLAB ProgrammingTechniques
MATLAB Programming
Techniques
MATLAB Programming
Techniques
MATLAB Programming
Techniques
!ext page
Try
Deter#ine $hich files are being accessed.
>> ic analysis_func
>> ic analysis_func *all
?bser"e ho$ local "ariables take precedence o"er functions.
>> ic mean *all
>> mean = 2>> ic mean
>> ic mean *all>> mean()
>> mean([ & %])>> clear mean
>> ic mean
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
10/20
Writing Functions
The M*TL*+-
#athEather than search e"ery$here on your co#puter and possibly your
net$ork/to deter#ine if analysis is a "alid co##and or function call&MATLA
has its o$nsearch path of directories $here it $ill look for code files.During installation& all files supplied $ith MATLA and anyinstalled
MathWorks! toolbo2es are placed on the search path. -f you create ne$
MATLA related files& you #ust ensure that the directories containing the
files are placed on the search path. Subdirectories #ust be e2plicitly
added& e"en if parent directories are on the path.
searchin order
To set and edit the search path& open the .et #ath dialog by clicking the
.et
#athbutton in the En/ironment section of the 0ome tab of the toolstrip'
The path can also be edited progra##atically using functions such as pat#&
a''pat#& rmpat#& and sa%pat#.
The order of the directories on the search path is i#portant if you ha"e
#orethan one file $ith the sa#e na#e independent of the e2tension/. Wh
MATLA looks for a file& only the one $ith highest precedence is foun?ther files $ith the sa#e na#e are said to be shadowed.
%se
function to deter#ine $hich instance of a file is beingaccessed.
the"#ic
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
11/20
Writing Functions
1ebugging
ecause function $orkspaces are local and te#porary& finding proble#s
$ithyour code can be difficult.
The MATLA :ditor has an integrated code analysis tool that pro"ides
acheck for synta2 errors as the code is being $ritten. 0or e2a#ple'
strings #issing a deli#iter / are colored red& $hile closed strings turn
purpleF code inside loops is indentedF closing parentheses are briefly
highlighted $ith their opening counterpart.Scripts and functions can in"oke other scripts and functions. 5ence& $herrors do occur& they #ay originate se"eral layers deep into the progressiofA s#all& s8uare bo2 in the upper right corner of the :ditor sho$s the
current
state of the code.
function calls. MATLA sho$s the error #essage fro# each functio
Careful re"ie$ of thisstack trace #ay re"eal the source of the
error.
:rror #essages in MATLA gi"e the line nu#ber $here the error
occurred.
Clicking the error #essage $ill open the appropriate file in the :ditor.
or poor code perfor#ance.
Additionally& specific proble#s $ithin the code appear $ith an orange or
redunderline. A description is sho$n $hene"er the #ouse is ho"ered o"er thehighlighted code.i#pro"e#ent.
So#eti#es the #essage suggests a correction or
A green bo2 indicates that the Code Analy4er could not detect any
synta2
errors or co##on proble#s. This does not #ean& ho$e"er& that the code
is necessarily free of run1ti#e errors.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Color Meaning
Green
?range
Eed
There are no detectable synta2 errors in the
code.
There is a potential for une2pected results
There are synta2 errors that $ill pre"ent codefro# running.
Try
3ie$ a "ersion of analysis_func that has a bug in it. %se the Cod
Analy4er #essages to find potential proble#s.
Try to call the function. Did it $orkH -f not& follo$ the error #essage
link to find $here the proble# occurred.
>> usage2020 = analysis_debug(!!!
"electricity#sage!$ls",%,enddate)
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
12/20
Writing Functions
Using
+rea"points-f an error #essage is not enough to diagnose a proble#& you can acti"ate
the
MATLA Debugger by setting a breakpoint in the :ditor. reakpoints
are specific lines of code $here you $ould like MATLA to stop
e2ecution and
6hold e"erything7 I that is& keep all
acti"eaccessible.
function $orkspaces open and
To set a breakpoint using the :ditor&
click a dash in the breakpoint colu#n
ne2t to the line nu#ber of an
>ou can use the .tep and Contin
controls in the 1ebug section of
Editor tab to step through the progr
one line at a ti#e 0(>/ to indicate t
MATLA has entered debug modor keyboard mode& hence the * in
pro#pt/.
indicates $here e2ecution is paused.
!ote The line of code indicated by
the arro$ has not yet been e2ecuted.
A hollo$ arro$ indicates that controlis in another function call.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Try
Set a breakpoint in analysis_'%!u.m near a line rele"ant tothe error #essage. Eerun the pre"ious co##and at the co##and
line to acti"ate debug #ode.
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
13/20
g
Examining
'alues:2a#ine "alues of "ariables $hen you $ant to see $hether a line of code
has
produced the e2pected result or not. -f the result is as e2pected& continue
running or step to the ne2t line. -f not& then that line& or a pre"ious line&
contains an error.
-n debug #ode& you can choose any acti"e $orkspace fro# the Functi
Call
.tac" in the 1ebug section of the Editor tab. The $orkspace "ariab
then appear in the Workspace bro$ser $here they can be e2a#ined in
3ariable :ditor or in the Co##and Windo$.
-n debug #ode& you can enter co##ands in the Co##and Windo$ to
e2a#ine "alues. -n the :ditor& if you position your cursor near a "ariable&
its current "alue pops up as a data tip. The data tip stays in "ie$ until you
#o"e the cursor.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Try
:2a#ine the di#ensions of the "ariables in analysis_'%!u.m
$hile in debug #ode. Locate and correct the run1ti#e error.
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
14/20
Ending 1ebugging
While debugging& you can change the "alue of a "ariable in the current$orkspace to see if a ne$ "alue produces the e2pected results. While the
progra#
Windo$
&stepping
is paused& assign a ne$ "alue to the "ariable in the Co##and
Workspace bro$ser& or Array :ditor& then continue running
or through the progra#. -f the ne$ "alue does not producethee2pected results& the progra# has another
proble#. To end debugging& click the 2uit 1ebugging button. After 8uittdebugging& the pause arro$s in the :ditor display no longer appear& a
the nor#al pro#pt >> reappears in the Co##and Windo$. >ou can
longer access the call stack.
After identifying a proble#& end the debugging session. >ou #ust end
a
debugging session if you $ant to change and sa"e a file to correct a
proble#& or if you $ant to run other functions in MATLA. -f you edit a
file $hile in debug #ode& you can get une2pected results $hen you run the
file.
After you think you ha"e identified and corrected a proble#& you c
disable
breakpoints so that the progra# ignores the#& or you can re#o"e th
entirely. Clicking a breakpoint dot clears it. Eight1clicking a breakpodot sho$s a conte2t #enu that $ill allo$ you to disable the breakpoint
B $ill appear through the dot/ or clear it.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Try
0ind and correct all bugs in analysis_'%!u.m. :2it debug
#ode& sa"e the file& and clear all breakpoints.
3erify that the function is no$ $orking correctly.
>> usage2020 = analysis_debug(!!!"electricity#sage!$ls",%,enddate)
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
15/20
created by a separate function.
Course Example:
*dding Model
#arameters
The function analysis_inputs.m i#ple#ents a #ore co#plicated
analysis of the electricity usage data& including a"eraging consecuti"e
blocksof #onths before fitting a polyno#ial to a subset of the a"eraged data.The function returns the predicted usage& and also optionally creates a
plot.A function call $ith si2 inputs is not easy to interpret. 0urther#ore& as pa
of
a larger application& so#e or all of these inputs #ay be re8uired as inpu
to other functions.
This #ore co#plicated algorith# re8uires #ore para#eters& $hich #eans
thatthis function takes si2 inputs'%%%%
%
The na#e of the data file
The degree of the polyno#ial to fit to the
data The future date at $hich to predict the
usage The nu#ber of #onths o"er $hich to
a"erageThe nu#ber of #onths to use as the data
subset to $hich the #odel is fittedA flag that specifies $hether or not to #ake the plot
-n situations like this& it is helpful to ha"e the function accept an input t
is a
collection of indi"idual para#eters. This is co##only achie"ed $
structures see page ()1(/& $hich allo$ you to co#bine data of di"e
types and si4es. 0urther#ore& structures use na#ed inde2ing& $hi#akes interpretation of the data organi4ation easier.
% Se"eral MATLA functions that i#ple#ent algorith#s $ith #any
optionstake this approach. The options are specified in a structure& $hich istypically
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Try
Call the analysis function $ith si2 inputs.
>> enddate = datetime(20&,,);
>> usage2020 = analysis_inputs(!!!"electricity#sage!$ls",%,enddate,!!!
2,20,true)
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
16/20
on as a
"ariable.
nting a finite
M*TL*+- 1ata Types See the docu#entation for details on the "arious nu#eric types' M*TL*
Language Fundamentals 1ata Types !umeric Types.
particular& note that there are particular rules for ho$ arith#etic
i#ple#ented $hen using nondouble "ariables. These rules
su##ari4ed on page A1(, in Appendi2 A 6MATLA Eeference7/.
The graphic belo$ sho$s the funda#ental data types
a"ailable
in
MATLA.A "ariable
ofdata.
any data type is an array $ith a characteristic organi4ation
ofM*TL*+ Langua>ou can con"ert bet$een data types'
Fundamentals 1ata Types 1ata Type Con/ersion. Con"ers
Array si4es range fro# 01by10 e#pty/ to the #a2i#u# si4e your co#puter#e#ory allo$s. MATLA puts no li#its on si4e.
functions areEeference7/.
su##ari4ed on page A1( in Appendi2 A 6MATL
>ou can create additional data types as user1defined
classes.
0unction handles and categorical arrays are not discussed
in
0unction handles pro"ide a $ay to store a reference to a functi
this course.
Categorical arrays
arenu#ber of categories.
intended to store te2t labels repres
e
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
17/20
Combining 0eterogeneous 1ata
with
.tructures>ou can use structure arrays to asse#ble data of dissi#ilar types and
si4es
into one "ariable. Structure arrays use na#ed referencing like tables& but
there is no re8uire#ent that the data confor# to a tabular arrange#ent.Data in structures arrays is referenced by na#edfields. The
co##and
+>> +.appl%s = 42;
appl%s 42
creates a structure + $ith a field
called appl%s& $hich takes the "alue of 42. As usual& referencing a none2istent fieldna#e $ill result in an error&assigning to a none2istent fieldna#e $ill cause that field to be
created'
b
-f + is already a structure& the field appl%s $ill be added to it if it doesnJte2ist already/.
>>
>>
x = +.oran%s;
+.oran%s = [,2,-];
%rror/
*-f + already e2ists& but is not a structure& a $arning $ill result& because + $ill
be con"erted to a structure.
+:ach field of a structure can contain data of different si4es and
types'appl%s 42
>> +.!ananas = r%%n;
!ananas r%%n
+ oran%s [,2,-]
appl%s 42
!ananas r%%n
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Try
Create a single structure containing necessary #odel infor#ation.
>> mymodel = struct(!!!
"datafile","electricity#sage!$ls",!!!"polydegree",%,"predictdate",enddate,!!!
"montag",2,"nummontmodel",20,!!!
"maeplot",true)
Pass a single structure argu#ent to a function that analy4es
electricity usage data.
>> edit analysis_struct
>> usage2020 = analysis_struct(mymodel)
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
18/20
.ummary
Creating and calling
functions
Workspace
s
Path and precedence
Debugging
Data types
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
19/20
Test 3our 4nowledge
;a#e'
). Which of the follo$ing is a "alid function
declarationH
A.
.
C.
D.
function [x,y] = foo(a,!)
function foo(a,!) = [x,y]
[x,y] = function foo(a,!)
[x,y] = foo(a,!)(.Suppose the $orkspace contains a "ector x and the function foo creates
a scalar "ariable also called x. What $ill happen to the "ector x if you
issue the co##and >> 1 = foo()H
*. Select all that apply/ Which of the follo$ing are "alid calls to afunction$ith the declaration line function = foo(a,!)H[x,y]A.
.-t $ill change to the scalar "alue defined in foo.
;othing& because the t$o "ariables are of
differenti.e.& a "ector cannot be changed to a scalar/.
di#ensions A.
.
C.
D.
:.
[x,y] = foo(a)
x = foo(a,!)C.;othing& because the "ector x is not passed
foo.
as an argu#ent to[x,y]
(x,y)
[x,y]
=
=
=
foo[a,!]
foo(a)
foo(a,!)D.
;othing& because foo #aintains its o$n $orkspace& so there is no
na#e conflict.
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#1
Writing Functions
-
7/26/2019 Mlbe 12 Functions Note
20/20
2014 by MathWorks, Inc. MATLAB Funda!nta"s 12#2