P. 1
ENGR-25 Lec-07 Sp12 Functions-3 Handles Types

|Views: 1|Likes:

See more
See less

05/06/2013

pdf

text

original

# Engr/Math/Physics 25

Chp3 MATLAB
Functions: Part3
Bruce Mayer, PE
BMayer@ChabotCollege.edu
Engineering/Math/Physics 25: Computational Methods
1

Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt

Learning Goals
 Understand the difference Built-In and User-Defined MATLAB Functions  Write User Defined Functions  Describe Global and Local Variables  When to use SUBfunctions as opposed to NESTED-Functions  Import Data from External Data-Files
• As generated, for example, by an Electronic Data-Acquisition System
Engineering/Math/Physics 25: Computational Methods
2

Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt

Functions (ReDeaux)
 MATLAB Has Two Types of Functions 1. Built-In Functions Provided by the Softeware
• e.g.; max, min, median

2. User-Defined Functions are .m-files that can accept InPut Arguments/Parameters and Return OutPut Values
Engineering/Math/Physics 25: Computational Methods
3

Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt

Function Handle (MATLAB help)
 MATLAB functions are written to NAMED files or are produced at the command line as ANONYMOUS functions.

 In either case, a function handle is used to pass the function as an input argument to a function function.
Engineering/Math/Physics 25: Computational Methods
4

Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt

For example.ppt . You can then name the handle if you wish. and use the handle to reference the function.Function Handles  You can create a function handle to any function by using the “at” sign. PE BMayer@ChabotCollege. you type >> sine_handle = @sin.  where sine_handle is a user-selected name for the handle (or NickName). Engineering/Math/Physics 25: Computational Methods 5 Bruce Mayer. to create a handle to the sine function. @.edu • ENGR-25_Functions-3. before the function name.

plot sinx over 0  x  6 as follows: >> plot([0:0.01:6].Function Handles cont  A common use of a function handle is to pass the function as an argument to another function.ppt . sine_handle([0:0. For example.01:6]))  The Result Engineering/Math/Physics 25: Computational Methods 6 Bruce Mayer. PE BMayer@ChabotCollege.edu • ENGR-25_Functions-3.

edu • ENGR-25_Functions-3. For example. but the concept can be extended to create. >> gen_plot(ln_handle. say.Function Handles cont  This is a rather cumbersome way to plot the sine function. interval) plot(interval. a general purpose plotting function that accepts a built-in function as an input.1:99) Bruce Mayer. PE BMayer@ChabotCollege. function p = gen_plot(fcn_handle. fcn_handle(interval))  Create a handle to the natural log (ln) function • Plot over 1→99 Engineering/Math/Physics 25: Computational Methods 7 >> ln_handle = @log.ppt .

02:10) Engineering/Math/Physics 25: Computational Methods 8 Bruce Mayer.ppt .edu • ENGR-25_Functions-3. PE BMayer@ChabotCollege.Function Handles cont  Can Pass a Function with @ sign handle >> gen_plot(@sech.0:.

Calling Functions  There are four ways to invoke. As a string expression. As an “inline” function object 4. As a function handle 3.edu • ENGR-25_Functions-3. or “call. These are: 1.m-file 2.” a function into action.  Examples of these ways follow for the fzero Built-in fcn which acts on the user-defined function parab.ppt Engineering/Math/Physics 25: Computational Methods 9 . which computes y = x2 − 4 Bruce Mayer. As a character string identifying the appropriate function . PE BMayer@ChabotCollege.

5). PE 5 BMayer@ChabotCollege. yplt = parab(xplt) plot(xplt.parab.m Graphed 25 20 15 xplt = linspace(-5.edu • ENGR-25_Functions-3.yplt) grid xlabel('x') ylabel('parab(x)') parab(x) 10 5 0 -5 -5 10 -4 -3 -2 -1 Engineering/Math/Physics 25: Computational Methods 0 x 1 2 3 4 Bruce Mayer.ppt .

value] = fzero('parab'.edu • ENGR-25_Functions-3.Calling Functions cont 1. As a character string identifying the appropriate function . [0 3]) x = 2 value = 0 Engineering/Math/Physics 25: Computational Methods 11 Bruce Mayer. PE BMayer@ChabotCollege. which is  The function may be called as follows.m-file.ppt . to compute the zero over the range: 0 ≤ x ≤ 3 >> [x.

PE BMayer@ChabotCollege.[0.Calling Functions cont 2. As a function handle to an existing function . val_0] = fzero(parab_inline. val0] = fzero(@parab. 3]) w = 2 val_0 = 0 Engineering/Math/Physics 25: Computational Methods 12 Bruce Mayer.^2-4'.m-file: >> [z.ppt . >> parab_inline = inline(parab1).edu • ENGR-25_Functions-3.[0. 3]) 3. >> [w. As an “inline” function object: >> parab1 = 'x.

>> [u.edu • ENGR-25_Functions-3. zero_u] = fzero(parab2. 3]) u = 2 zero_u = 0 Engineering/Math/Physics 25: Computational Methods 13 Bruce Mayer.Calling Functions cont 4.ppt .^2-4'. zero_u] = fzero('x.[0. PE BMayer@ChabotCollege.^2-4'. As a string expression: >> parab2 = 'x.[0. 3])  Or as >> [u.

which are normally not visible outside of their defining . • If we give a “SubFunction” a handle. another advantage of using a function handle is that it provides access to subfunctions. then we can “reach into” the function file to engage the useful SubFcn withOUT using the main function Bruce Mayer. followed by method 1. In addition to speed improvement. or nickname. PE BMayer@ChabotCollege.ppt Engineering/Math/Physics 25: Computational Methods 14 .Calling Functions cont   The function handle method (method 2) is the fastest method.edu • ENGR-25_Functions-3.m-file.

ppt  Engineering/Math/Physics 25: Computational Methods 15 . PE BMayer@ChabotCollege. and these are only visible to the primary function or to other subfunctions in the same file.Types of User Defined Fcns  The PRIMARY function is the first function in a . . Bruce Mayer. Additional functions within the file are called subfunctions.m-files can contain code for more than one function. which can serve as subroutines that support the primary function. Following the primary function in the same file can be any number of subfunctions. That is.edu • ENGR-25_Functions-3.m-file and typically contains the main program.

m-file in which it is defined.ppt .  Engineering/Math/Physics 25: Computational Methods 16 Bruce Mayer. but if the function name differs from the file name.m-file that we can call from the MATLAB Command Window or from another . you must use the FILE name to invoke the function. PE BMayer@ChabotCollege. • We normally use the same name for the function and its file.PRIMARY Function  Usually the primary function is the ONLY function in a .edu • ENGR-25_Functions-3.m-file function You invoke the Primary function using the name of the .

• More on anonymous fcns in a few slides Bruce Mayer. PE BMayer@ChabotCollege. anonymous functions provide a quick way of making a function from any MATLAB expression withOUT the need to create.ppt Engineering/Math/Physics 25: Computational Methods 17 .m-file for it. and save a file.  Thus. name. • You can construct an anonymous function either at the MATLAB command line or from within another function or script.edu • ENGR-25_Functions-3.Types of User Defined Fcns  ANONYMOUS functions enable creation of a simple function withOUT needing to write a separate a .

PE BMayer@ChabotCollege.Types of User Defined Fcns  SUBFUNCTIONS are placed in the primary function and are called by the primary fcn • You can use multiple functions within a single primary function m-file  NESTED functions are functions defined within another function.ppt Engineering/Math/Physics 25: Computational Methods 18 . • They can help to improve the readability of your program and also give you more flexible access to variables in the . Produce Nesting “Levels”  The difference between nested functions and subfunctions is that subfunctions normally cannot be accessed outside of their primary function file Bruce Mayer.m-file.edu • ENGR-25_Functions-3.

They are similar to overloaded functions in any object-oriented language.m-file function in the parent directory • Search PATHs will NOT work.Types of User Defined Fcns  OVERLOADED functions are functions that respond differently to different types of input arguments. PE BMayer@ChabotCollege. an overloaded function can be created to treat integer inputs differently than inputs of class double (precision). They can be called only from a .  PRIVATE functions enable you to restrict access to a function. • For example. Bruce Mayer.ppt Engineering/Math/Physics 25: Computational Methods 19 .edu • ENGR-25_Functions-3.

edu • ENGR-25_Functions-3. Engineering/Math/Physics 25: Computational Methods 20 Bruce Mayer. PE BMayer@ChabotCollege.ppt .Function Function  The term function function is not a separate function type but refers to any function that accepts another function as an input argument. such as the function fzero or fminbnd  You can pass a function to another function using a function handle.

edu • ENGR-25_Functions-3. valid MATLAB expression.ppt .Anonymous Functions  The syntax for creating an anonymous function from an expression is fhandle = @(arglist) expr  Where • The Term arglist is a comma-separated list of input arguments to be passed to the function • The Term expr is any single. Engineering/Math/Physics 25: Computational Methods 21 Bruce Mayer. PE BMayer@ChabotCollege.

ppt Engineering/Math/Physics 25: Computational Methods 22 .edu • ENGR-25_Functions-3. y A . y B .Anonymous Fcn  Unit Vector  Consider a Direction in 3D space defined by LoA running from Pt-A to Pt-B with CoOrds as shown  Define DIRECTION Vector AB ˆ AB  xB  x A i  xB . z B  û x A . z A   yB  y A  ˆ j  z B  z A k  Or using Δ Notation ˆ  y ˆ ˆ AB  xABi AB j  z AB z Bruce Mayer. PE BMayer@ChabotCollege.

z A   Now AB has the same Direction as u. but a different length Engineering/Math/Physics 25: Computational Methods 23  “Normalizing” AB to its Length will produce a vector of unit Length.edu • ENGR-25_Functions-3. y B .Anonymous Fcn  Unit Vector  Next Calculate the Geometric Length. AB. PE BMayer@ChabotCollege.ppt . u Bruce Mayer.e. y A . i. z B  AB  AB  LAB 2 2 2  x AB  y AB  z AB û x A . of The Direction Vector AB using Pythagorus  xB ..

ppt .Anonymous Fcn  Unit Vector  Normalize AB to Produce û  xB . z B  AB AB ˆ u  LAB AB  ˆ ˆ  yˆ xi j  zk 2 2 2 x AB  y AB  z AB û x A . y A . z A   the Δ’s for this case  Create MATLAB x AB  40m y AB  80m Anonymous Fcn: uV(Δx. y B . Δy.edu • ENGR-25_Functions-3. Δz) z AB  30m Engineering/Math/Physics 25: Computational Methods 24 Bruce Mayer. PE BMayer@ChabotCollege.

y A .ppt . y B .edu • ENGR-25_Functions-3. z B  û x A . PE BMayer@ChabotCollege.Anonymous Fcn  Unit Vector  Write Anon Fcn uV completely in the COMMAND Window  Test using conditions Given at Right  xB . z A  • Also find Space Angles by acosd(uAB) Engineering/Math/Physics 25: Computational Methods 25 Bruce Mayer.

delY.17) uVa = 0. dz) [dx dy dz]/sqrt(sum(dx^2 + dy^2 + dz^2)) uV2 = @(dx.8046 0.3607 -0.4717 >> SpcQ = acosd(uVa) SpcQ = 68.dz]/sqrt(sum(dx^2+dy^2+dz^2)) >> uVb = uV2(13.ppt Engineering/Math/Physics 25: Computational Methods .dy.delZ]/norm([delX.-29.delZ)[delX.delY. PE BMayer@ChabotCollege.dy.8046 0.edu • ENGR-25_Functions-3.delY.dz)[dx.8572 143.TWO versions of uV anon fcn >> uV1 = @(delX.8568 Bruce Mayer.-29.4717 >> uV2 = @(dx.3607 -0.delZ]) >> uVa = uV1(13.5740 26 61. dy.delY.17) uVb = 0. delZ) [delX delY delZ]/norm([delX delY delZ]) uV1 = @(delX.

log(x+1) cos_ln = @(x)7*cos(x)log(x+1) >> x_zero = fzero(cos_ln. and use “fzero” to find x that satisfies eqn near x=2 7 cos x  ln x  1  0 Engineering/Math/Physics 25: Computational Methods 27 1.edu • ENGR-25_Functions-3. PE BMayer@ChabotCollege. 2) x_zero = 7 cos x  ln x  1  Collect Terms on One Side.Anonymous Function in fzero  Solve the Transcendental Equation >> cos_ln = @(x) 7*cos(x) .ppt .4429 Bruce Mayer.

4429 >> Z2 = fzero(cos_ln.8].9705 >> Z3 = fzero(cos_ln. grid.5425 0 1 2 3 4 u 5 6 7 8 Engineering/Math/Physics 25: Computational Methods 28 Bruce Mayer.v. 300). 2. xZ. >> Z1 = fzero(cos_ln.5*pi.8) Z3 = 7.edu • ENGR-25_Functions-3.2) Z1 = 1. >> plot(u.ppt . PE BMayer@ChabotCollege. >> xZ = [0. >> v = cos_ln(u). yZ = [0. 'LineWidth'. xlabel('u').5) Z2 = 4.5π 8 6 4 2 0 v -2 -4 -6 -8 -10 >> u = linspace(0.yZ.@Cos_ln (x) Graphed: 0-2. ylabel('v'). 0].3).

9428i >> nth_root(10./n).^(1.ppt .1623 2.1414 >> z1 = nth_root(-99.4678 Bruce Mayer.3) z1 = 2. PE BMayer@ChabotCollege.ANONYMOUS Function example  Build.1544 1.3) z = 3.1683 + 1. >> z = nth_root(31.5849 Engineering/Math/Physics 25: Computational Methods 29 1. 1n a function that returns the nth Root of a Scalar Base zB >> nth_root = @(B. [2:6]) ans = 3. completely in the Command Window.n) B.4.edu • ENGR-25_Functions-3.7783 1.

• For example. 10) Engineering/Math/Physics 25: Computational Methods 30 Bruce Mayer.edu • ENGR-25_Functions-3.50*x + 5. >>fminbnd(poly1.50*x + 5. -10.^2 . to find the minimum of the polynomial 4x2 – 50x + 5 over the interval [–10.2500  Omit the Handle for a One-Time fcn use fminbnd(@(x) 4*x.ppt . PE BMayer@ChabotCollege.^2 . 10] >>poly1 = @(x) 4*x.Anonymous Functions cont  You can pass the handle of an anonymous function to other functions. 10) ans = 6. -10.

It is composed of the fcns g(y) = 5sin(y) and y = f(z) = z3  h(x) = g(f(x)) • In the following session the function whose handle is h calls the functions whose handles are f and g.9468 Bruce Mayer. PE BMayer@ChabotCollege.Calling One Fcn within Another   One anonymous function can call another to implement function composition.^3.edu • ENGR-25_Functions-3. >>g = @(x) 5*sin(x). >>h = @(x) g(f(x)). Consider the function h(x) = 5sin(x3). >>h(2) ans = 4. >>f = @(x) x.ppt Engineering/Math/Physics 25: Computational Methods 31 .

as for example with the variables A and B in plane = @(x. 2.^3.Variables and Anonymous Fcns  Variables can appear in anonymous functions in two ways: 1. As variables PreDefined in the body of the expression.edu • ENGR-25_Functions-3. PE BMayer@ChabotCollege.y) A*x + B*y Engineering/Math/Physics 25: Computational Methods 32 Bruce Mayer. as for example f = @(x) x. As variables specified in the argument list.ppt .

>> P2 = plane (1. >> A = 3. B = 7.y) A*x + B*y >> P1 = plane (1.2) P1 = 17 >> A = 9. their values associated with the handle do NOT change. >> plane = @(x. PE BMayer@ChabotCollege.ppt Engineering/Math/Physics 25: Computational Methods 33 .Vars & Anonymous-Fcns cont  When the function is created MATLAB captures the values of these variables and retains those values for the lifetime of the function handle. • If the values of A or B are changed after the handle is created. B = 14.2) P2 = 17 Bruce Mayer.edu • ENGR-25_Functions-3.

 Subfunctions are normally “visible” only to the primary function and other subfunctions in the same file.m-file may contain more than one user-defined function.edu • ENGR-25_Functions-3.SubFunctions  A function . whose name is the same as the m-file name. • that is. PE BMayer@ChabotCollege. they normally cannot be called by programs or functions outside the primary fcn file – this limitation can be removed with fcn handles Bruce Mayer. All other functions in the file are called subfunctions.ppt Engineering/Math/Physics 25: Computational Methods 34 . • • The first defined function in the file is called the primary function.

Next.SubFunctions cont  Create the primary function first with a function definition line and its defining code. but function names must be unique within the primary function . create within the .m-file with this function name as usual.m-file.edu • ENGR-25_Functions-3.ppt .  Engineering/Math/Physics 25: Computational Methods 35 Bruce Mayer. PE BMayer@ChabotCollege. and name the .m-file each subfunction with its own function definition line and defining code • The order of the subfunctions does not matter.

2) == 1 m = w((n+1) / 2). % Subfunction function m = median(v. med] = newstatsSF(u) % Primary function % Bruce Mayer. function a = mean(v. end Engineering/Math/Physics 25: Computational Methods 36 % Subfunction Bruce Mayer.m (SHOULD match fcn name) % NEWSTATS Find mean and median with internal functions. PE * 06Feb12 * ENGR25 % file = newstatsSF. n) % Calculate median. PE BMayer@ChabotCollege. w = sort(v). avg = mean(u. med = median(u. n). else m = (w(n/2) + w(n/2+1)) / 2. a = sum(v)/n. n).ppt . if rem(n. n = length(u). n) % Calculate average.edu • ENGR-25_Functions-3.SubFunction Example function [avg.

ppt .1168 Engineering/Math/Physics 25: Computational Methods 37 Bruce Mayer.SubFunction Example Results >> w = [12:0. >> z = log(w).*(cos(w)). zmed] = newstatsSF(z) zavg = 2.37:209]. PE BMayer@ChabotCollege.^2.2590 zmed = 2. >> [zavg.edu • ENGR-25_Functions-3.

m-files on your search path Engineering/Math/Physics 25: Computational Methods 38 Bruce Mayer. then checks to see if it is a private function – which is a function m-file residing in the PRIVATE subdirectory of the calling function 4.Function-Call Precedence  The order in which MATLAB checks for functions is very important. PE BMayer@ChabotCollege. first checks to see if the function is a built-in function such as sin.m-file. Next it checks to see if it is a subfunction in a primary function . Then MATLAB checks for normal .m-file 3. When a function is called from within an .edu • ENGR-25_Functions-3. MATLAB 1. 2.ppt .

Function-Call Precedence cont  Thus. you may use subfunctions with the same name as another existing m-file • This feature allows you to name subfunctions without being concerned about whether another function exists with the same name.edu • ENGR-25_Functions-3. because MATLAB checks for a subfunction before checking for private and standard . so you need not choose long function names to avoid conflicts This feature also protects you from using another function unintentionally.ppt • Engineering/Math/Physics 25: Computational Methods 39 .m-file functions. Bruce Mayer. PE BMayer@ChabotCollege.

• The function residual_x is the primary function.ppt . one which gives the Root-Mean Square (RMS) value. Engineering/Math/Physics 25: Computational Methods 40 Bruce Mayer.edu • ENGR-25_Functions-3. function r = residual_x(a) r = a .SubFunction Example  This example shows how the MATLAB m-function mean can be superceded by our own definition of the mean. % function w = mean(z) w = sqrt(sum(z. PE BMayer@ChabotCollege. • The function mean is a subfunction.^2))/length(z).mean(a).

8284 Use RMS residual fcn on [4.ppt Engineering/Math/Physics 25: Computational Methods 41 .-4] Note: RMS mean = 2. >> r1 = residual_x(v) r1 = 1. PE BMayer@ChabotCollege.8284  The ReDefined mean does NOT change the standard MATLAB version >> r2 = v .mean(v) r2 = 4 -4 Bruce Mayer.m-File • Suggest checking mean in MATLAB Help >> v = [ 4 -4].SubFunction Example cont   Note that mean is a std MATLAB .edu • ENGR-25_Functions-3.1716 -6.

we can use a function handle to allow access to the subfunction from outside the m-file Bruce Mayer. of files that define your fcns • For example. we would have had to define a separate . if it were not for the subfunction mean in the previous example.SubFunction Assessment  The use of subfunctions enables you to reduce the no. PE BMayer@ChabotCollege.edu • ENGR-25_Functions-3.m-file for our mean function and give it a different name so as not to confuse it with the MATLAB fcn of the same name  Subfunctions are normally visible only to the primary function and other subfunctions in the same file • However.ppt Engineering/Math/Physics 25: Computational Methods 42 .

ppt .edu • ENGR-25_Functions-3.All Done for Today Some Root Mean Square Calculations Engineering/Math/Physics 25: Computational Methods 43 Bruce Mayer. PE BMayer@ChabotCollege.

PE BMayer@ChabotCollege.edu Bruce Mayer. PE Licensed Electrical & Mechanical Engineer f x   2 x  7 x  9 x  6 3 2 Engineering/Math/Physics 25: Computational Methods 44 BMayer@ChabotCollege.edu • ENGR-25_Functions-3.Engr/Math/Physics 25 Appendix Bruce Mayer.ppt .

yplt = cos_ln(xplt).5 x 2 2.@Cos_ln (x) Graphed 8 6 4 2 y = cos n(x) l 0 -2 cos_ln = @(x) 7*cos(x) .5 1 1.log(x+1) xplt = linspace(0.edu • ENGR-25_Functions-3.3).yplt) grid -8 xlabel('x') ylabel('y = cos_ln(x)') -4 -10 0 0.5 Bruce Mayer. PE BMayer@ChabotCollege.ppt 3 Engineering/Math/Physics 25: Computational Methods 45 . -6 plot(xplt.

Anonymous Fcn  Unit Vector >> uV1 = @(delX. -9.*[delX delY delZ]))).7448 0.3310 >> uV2 = @(delX. delY.7448 0. delZ) [delX delY delZ]/(sqrt(sum([delX delY delZ]. >> uVtest1 = uV1(7.3310 Engineering/Math/Physics 25: Computational Methods 46 Bruce Mayer. 4) uVtest1 = 0.edu • ENGR-25_Functions-3. 4) uVtest2 = 0. -9.ppt . >> uVtest2 = uV2(7. delZ) [delX delY delZ]/norm([delX delY delZ]). delY. PE BMayer@ChabotCollege.5793 -0.5793 -0.

0054 Engineering/Math/Physics 25: Computational Methods 47 71.4240 0.3180 û >> SpcAng = acosd(uT) SpcAng = 115. PE BMayer@ChabotCollege.edu • ENGR-25_Functions-3.8480 0.4580 Bruce Mayer.Anonymous Fcn  Unit Vector  the Δ’s for this case x AB  40m y AB  80m z AB  30m  Use uv2 to find uT = -0.ppt .0873 32.

[4.Anonymous Fcns: Multi-Inputs  You can create anonymous functions having more than one input. PE BMayer@ChabotCollege.^2).7].0000 13.ppt .11]) ans = 5. define the function >> pythag = @(x.^2 + y. For pythag  x 2  y 2 example.4009 >> pythag([3.17) c = 21.edu • ENGR-25_Functions-3.y) sqrt(x.0384 Engineering/Math/Physics 25: Computational Methods 48 Bruce Mayer. >> c = pythag(13.

scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->