Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding MATLAB Functions: Built-In, User-Defined, and Anonymous Functions, Slides of Calculus for Engineers

An overview of various types of functions in matlab, including built-in functions, user-defined functions (.m-files), and anonymous functions. It covers topics such as function handles, calling functions, and the differences between subfunctions, nested functions, and overloaded functions. The document also includes examples of anonymous functions and their applications.

Typology: Slides

2012/2013

Uploaded on 03/26/2013

abduu
abduu 🇮🇳

4.4

(47)

200 documents

1 / 45

Toggle sidebar

Related documents


Partial preview of the text

Download Understanding MATLAB Functions: Built-In, User-Defined, and Anonymous Functions and more Slides Calculus for Engineers in PDF only on Docsity! 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 Docsity.com 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 Docsity.com Function Handles cont • A common use of a function handle is to pass the function as an argument to another function. For example, plot sinx over 0 ≤ x ≤ 6 as follows: >> plot([0:0.01:6], sine_handle([0:0.01:6]))  The Result Docsity.com Function Handles cont • This is a rather cumbersome way to plot the sine function, but the concept can be extended to create, say, a general purpose plotting function that accepts a built-in function as an input. For example, function p = gen_plot(fcn_handle, interval) plot(interval, fcn_handle(interval))  Create a handle to the natural log (ln) function • Plot over 1→99 >> ln_handle = @log; >> gen_plot(ln_handle,1:99) Docsity.com Function Handles cont • Can Pass a Function with @ sign handle >> gen_plot(@sech,0:.02:10) Docsity.com Calling Functions cont 1. As a character string identifying the appropriate function .m-file, which is  The function may be called as follows, to compute the zero over the range: 0 ≤ x ≤ 3 >> [x, value] = fzero('parab', [0 3]) x = 2 value = 0 Docsity.com Calling Functions cont 2. As a function handle to an existing function .m-file: >> [z, val0] = fzero(@parab,[0, 3]) 3. As an “inline” function object: >> parab1 = 'x.^2-4'; >> parab_inline = inline(parab1); >> [w, val_0] = fzero(parab_inline,[0, 3]) w = 2 val_0 = 0 Docsity.com Calling Functions cont 4. As a string expression: >> parab2 = 'x.^2-4'; >> [u, zero_u] = fzero(parab2,[0, 3])  Or as >> [u, zero_u] = fzero('x.^2-4',[0, 3]) u = 2 zero_u = 0 Docsity.com PRIMARY Function • Usually the primary function is the ONLY function in a .m-file that we can call from the MATLAB Command Window or from another .m-file function • You invoke the Primary function using the name of the .m-file in which it is defined. – We normally use the same name for the function and its file, but if the function name differs from the file name, you must use the FILE name to invoke the function. Docsity.com Types of User Defined Fcns • ANONYMOUS functions enable creation of a simple function withOUT needing to write a separate a .m-file for it. – You can construct an anonymous function either at the MATLAB command line or from within another function or script. • Thus, anonymous functions provide a quick way of making a function from any MATLAB expression withOUT the need to create, name, and save a file. – More on anonymous fcns in a few slides Docsity.com 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. – They can help to improve the readability of your program and also give you more flexible access to variables in the .m-file. Produce Nesting “Levels” • The difference between nested functions and subfunctions is that subfunctions normally cannot be accessed outside of their primary function file Docsity.com 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, valid MATLAB expression. Docsity.com 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 ( ) ( ) ( )kzz jyy ixxAB AB AB AB  − +− +−= ˆ ˆ  Or using Δ Notation zzjyixAB ABABAB ˆˆˆ ∆+∆+∆= û ( )BBB zyx ,, ( )AAA zyx ,, Docsity.com Anonymous Fcn  Unit Vector • Next Calculate the Geometric Length, AB, of The Direction Vector AB using Pythagorus  “Normalizing” AB to its Length will produce a vector of unit Length; i.e., u 222 ABABAB AB zyx LABAB ∆+∆+∆= ==  Now AB has the same Direction as u, but a different length û ( )BBB zyx ,, ( )AAA zyx ,, Docsity.com TWO versions of uV anon fcn >> uV1 = @(delX, delY, delZ) [delX delY delZ]/norm([delX delY delZ]) uV1 = @(delX,delY,delZ)[delX,delY,delZ]/norm([delX,delY,delZ]) >> uVa = uV1(13,-29,17) uVa = 0.3607 -0.8046 0.4717 >> uV2 = @(dx, dy, dz) [dx dy dz]/sqrt(sum(dx^2 + dy^2 + dz^2)) uV2 = @(dx,dy,dz)[dx,dy,dz]/sqrt(sum(dx^2+dy^2+dz^2)) >> uVb = uV2(13,-29,17) uVb = 0.3607 -0.8046 0.4717 >> SpcQ = acosd(uVa) SpcQ = 68.8572 143.5740 61.8568 Docsity.com Anonymous Function in fzero • Solve the Transcendental Equation ( )1lncos7 += xx  Collect Terms on One Side, and use “fzero” to find x that satisfies eqn near x = 2 ( ) 01lncos7 =+− xx >> cos_ln = @(x) 7*cos(x) - log(x+1) cos_ln = @(x)7*cos(x)- log(x+1) >> x_zero = fzero(cos_ln, 2) x_zero = 1.4429 Docsity.com @Cos_ln (x) Graphed: 0-2.5π 0 1 2 3 4 5 6 7 8 -10 -8 -6 -4 -2 0 2 4 6 8 u v >> u = linspace(0, 2.5*pi, 300); >> v = cos_ln(u); >> xZ = [0,8]; yZ = [0, 0]; >> plot(u,v, xZ,yZ, 'LineWidth',3), grid, xlabel('u'), ylabel('v'); >> Z1 = fzero(cos_ln,2) Z1 = 1.4429 >> Z2 = fzero(cos_ln,5) Z2 = 4.9705 >> Z3 = fzero(cos_ln,8) Z3 = 7.5425 Docsity.com Calling One Fcn within Another • One anonymous function can call another to implement function composition. • Consider the function h(x) = 5sin(x3). 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. >>f = @(x) x.^3; >>g = @(x) 5*sin(x); >>h = @(x) g(f(x)); >>h(2) ans = 4.9468 Docsity.com Variables and Anonymous Fcns • Variables can appear in anonymous functions in two ways: 1. As variables specified in the argument list, as for example f = @(x) x.^3; 2. As variables PreDefined in the body of the expression, as for example with the variables A and B in plane = @(x,y) A*x + B*y Docsity.com 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, their values associated with the handle do NOT change. >> A = 3; B = 7; >> plane = @(x,y) A*x + B*y >> P1 = plane (1,2) P1 = 17 >> A = 9; B = 14; >> P2 = plane (1,2) P2 = 17 Docsity.com SubFunction Example function [avg, med] = newstatsSF(u) % Primary function % Bruce Mayer, PE * 06Feb12 * ENGR25 % file = newstatsSF.m (SHOULD match fcn name) % NEWSTATS Find mean and median with internal functions. n = length(u); avg = mean(u, n); med = median(u, n); function a = mean(v, n) % Subfunction % Calculate average. a = sum(v)/n; function m = median(v, n) % Subfunction % Calculate median. w = sort(v); if rem(n, 2) == 1 m = w((n+1) / 2); else m = (w(n/2) + w(n/2+1)) / 2; end Docsity.com SubFunction Example Results >> w = [12:0.37:209]; >> z = log(w).*(cos(w)).^2; >> [zavg, zmed] = newstatsSF(z) zavg = 2.2590 zmed = 2.1168 Docsity.com Function-Call Precedence • The order in which MATLAB checks for functions is very important. When a function is called from within an .m-file, MATLAB 1. first checks to see if the function is a built-in function such as sin. 2. Next it checks to see if it is a subfunction in a primary function .m-file 3. 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. Then MATLAB checks for normal .m-files on your search path Docsity.com SubFunction Example cont • Note that mean is a std MATLAB .m-File – Suggest checking mean in MATLAB Help • Use RMS residual fcn on [4,-4] >> v = [ 4 -4]; >> r1 = residual_x(v) r1 = 1.1716 -6.8284  The ReDefined mean does NOT change the standard MATLAB version >> r2 = v - mean(v) r2 = 4 -4 Note: RMS mean = 2.8284 Docsity.com SubFunction Assessment • The use of subfunctions enables you to reduce the no. of files that define your fcns – For example, if it were not for the subfunction mean in the previous example, we would have had to define a separate .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, we can use a function handle to allow access to the subfunction from outside the m-file Docsity.com @Cos_ln (x) Graphed 0 0.5 1 1.5 2 2.5 3 -10 -8 -6 -4 -2 0 2 4 6 8 x y = co s l n( x) cos_ln = @(x) 7*cos(x) - log(x+1) xplt = linspace(0,3); yplt = cos_ln(xplt); plot(xplt,yplt) grid xlabel('x') ylabel('y = cos_ln(x)') Docsity.com
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved