1 / 48

Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu

Engr/Math/Physics 25. Chp3 MATLAB Functions: Part3. Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu. Learning Goals. Understand the difference Built-In and User-Defined MATLAB Functions Write User Defined Functions

sydney
Download Presentation

Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Engr/Math/Physics 25 Chp3 MATLABFunctions: Part3 Bruce Mayer, PE Licensed Electrical & Mechanical EngineerBMayer@ChabotCollege.edu

  2. 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

  3. Functions (ReDeaux) • MATLAB Has Two Types of Functions • Built-In Functions Provided by the Softeware • e.g.; max, min, median • User-DefinedFunctions are .m-files that can accept InPut Arguments/Parameters and Return OutPut Values

  4. 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.

  5. You can create a function handle to any function by using the “at” sign, @, before the function name. You can then name the handle if you wish, and use the handle to reference the function. For example, to create a handle to the sine function, you type Function Handles >> sine_handle = @sin; • where sine_handle is a user-selected name for the handle (or NickName).

  6. 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: Function Handles cont >> plot([0:0.01:6], sine_handle([0:0.01:6])) • The Result

  7. 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 Handles cont 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)

  8. Can Pass a Function with @ sign handle Function Handles cont >> gen_plot(@sech,0:.02:10)

  9. There are four ways to invoke, or “call,” a function into action. These are: As a character string identifying the appropriate function .m-file As a function handle As an “inline” function object As a string expression. Examples of these ways follow for the fzero Built-in fcn which acts on the user-defined function parab, which computes y = x2− 4 Calling Functions

  10. parab.m Graphed xplt = linspace(-5,5); yplt = parab(xplt) plot(xplt,yplt) grid xlabel('x') ylabel('parab(x)')

  11. As a character string identifying the appropriate function .m-file, which is Calling Functions cont • 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

  12. As a function handle to an existing function .m-file: Calling Functions cont >> [z, val0] = fzero(@parab,[0, 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

  13. As a string expression: Calling Functions cont >> 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

  14. The function handle method (method 2) is the fastest method, followed by method 1. In addition to speed improvement, another advantage of using a function handle is that it provides access to subfunctions, which are normally not visible outside of their defining .m-file. If we give a “SubFunction” a handle, or nickname, then we can “reach into” the function file to engage the useful SubFcn withOUT using the main function Calling Functions cont

  15. The PRIMARY function is the first function in a .m-file and typically contains the main program. Following the primary function in the same file can be any number of subfunctions, which can serve as subroutines that support the primary function. That is, .m-files can contain code for more than one function. Additional functions within the file are called subfunctions, and these are only visible to the primary function or to other subfunctions in the same file. Types of User Defined Fcns

  16. 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. PRIMARY Function

  17. 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 Types of User Defined Fcns

  18. 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 Types of User Defined Fcns

  19. OVERLOADED functions are functions that respond differently to different types of input arguments. They are similar to overloaded functions in any object-oriented language. For example, an overloaded function can be created to treat integer inputs differently than inputs of class double (precision). PRIVATE functions enable you to restrict access to a function. They can be called only from a .m-file function in the parent directory Search PATHs will NOT work. Types of User Defined Fcns

  20. 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.

  21. The syntax for creating an anonymous function from an expression is Anonymous Functions 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.

  22. Consider a Direction in 3D space defined by LoA running from Pt-A to Pt-B with CoOrds as shown Anonymous Fcn Unit Vector • Define DIRECTION Vector AB • Or using Δ Notation

  23. Next Calculate the Geometric Length, AB, of The Direction Vector AB using Pythagorus Anonymous Fcn Unit Vector • “Normalizing” AB to its Length will produce a vector of unit Length; i.e., u • Now AB has the same Direction as u, but a different length

  24. Normalize AB to Produce û Anonymous Fcn Unit Vector • the Δ’s for this case • Create MATLAB Anonymous Fcn:uV(Δx, Δy, Δz)

  25. Anonymous Fcn Unit Vector • Write Anon FcnuV completely in the COMMAND Window • Test using conditions Given at Right Time forLiveDemo • Also find Space Angles by acosd(uAB)

  26. TWO versions of uV anon fcn >> uV1 = @(delX, delY, delZ) [delXdelYdelZ]/norm([delXdelYdelZ]) 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 dydz]/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

  27. Solve the Transcendental Equation Anonymous Function in fzero >> 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 Time forLiveDemo • Collect Terms on One Side, and use “fzero” to find x that satisfies eqn near x = 2

  28. @Cos_ln (x)Graphed: 0-2.5π >> 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

  29. Build, completely in the Command Window, a function that returns thenth Root of a Scalar Base ANONYMOUS Function example >> nth_root = @(B,n) B.^(1./n); >> z = nth_root(31,3) z = 3.1414 >> z1 = nth_root(-99,4.3) z1 = 2.1683 + 1.9428i >> nth_root(10, [2:6]) ans = 3.1623 2.1544 1.7783 1.5849 1.4678

  30. You can pass the handle of an anonymous function to other functions. For example, to find the minimum of the polynomial 4x2– 50x + 5 over the interval [–10, 10] Anonymous Functions cont >>poly1 = @(x) 4*x.^2 - 50*x + 5; >>fminbnd(poly1, -10, 10) ans = 6.2500 • Omit the Handle for a One-Time fcn use fminbnd(@(x) 4*x.^2 - 50*x + 5, -10, 10)

  31. 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. Calling One Fcn within Another >>f = @(x) x.^3; >>g = @(x) 5*sin(x); >>h = @(x) g(f(x)); >>h(2) ans = 4.9468

  32. Variables can appear in anonymous functions in two ways: As variables specified in the argument list, as for example f = @(x) x.^3; 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 Variables and Anonymous Fcns

  33. 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. Vars & Anonymous-Fcns cont >> 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

  34. A function .m-file may contain more than one user-defined function. The first defined function in the file is called the primary function, whose name is the same as the m-file name. All other functions in the file are called subfunctions. Subfunctions are normally “visible” only to the primary function and other subfunctions in the same file; that is, they normally cannot be called by programs or functions outside the primary fcn file this limitation can be removed with fcn handles SubFunctions

  35. Create the primary function first with a function definition line and its defining code, and name the .m-file with this function name as usual. Next, create within the .m-file each subfunction with its own function definition line and defining code The order of the subfunctions does not matter, but function names must be unique within the primary function .m-file. SubFunctions cont

  36. 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

  37. SubFunction Example Results >> w = [12:0.37:209]; >> z = log(w).*(cos(w)).^2; >> [zavg, zmed] = newstatsSF(z) zavg = 2.2590 zmed = 2.1168

  38. The order in which MATLAB checks for functions is very important. When a function is called from within an .m-file, MATLAB first checks to see if the function is a built-in function such as sin. Next it checks to see if it is a subfunctionin a primary function .m-file 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 Then MATLAB checks for normal .m-files on your search path Function-Call Precedence

  39. Thus, because MATLAB checks for a subfunction before checking for private and standard .m-file functions, 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, so you need not choose long function names to avoid conflicts This feature also protects you from using another function unintentionally. Function-Call Precedence cont

  40. This example shows how the MATLAB m-function mean can be superceded by our own definition of the mean, one which gives the Root-Mean Square (RMS) value. The function mean is a subfunction. The function residual_x is the primary function. SubFunction Example function r = residual_x(a) r = a - mean(a); % function w = mean(z) w = sqrt(sum(z.^2))/length(z);

  41. Note that mean is a std MATLAB .m-File Suggest checking mean in MATLAB Help Use RMS residual fcn on [4,-4] SubFunction Example cont >> v = [ 4 -4]; >> r1 = residual_x(v) r1 = 1.1716 -6.8284 Note: RMS mean = 2.8284 • The ReDefined meandoes NOT change the standard MATLAB version >> r2 = v - mean(v) r2 = 4 -4

  42. 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 SubFunction Assessment

  43. All Done for Today Some RootMean SquareCalculations

  44. Engr/Math/Physics 25 Appendix Time For Live Demo Bruce Mayer, PE Licensed Electrical & Mechanical EngineerBMayer@ChabotCollege.edu

  45. @Cos_ln (x) Graphed 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)')

  46. Anonymous Fcn Unit Vector >> uV1 = @(delX, delY, delZ) [delXdelYdelZ]/(sqrt(sum([delXdelYdelZ].*[delXdelYdelZ]))); >> uVtest1 = uV1(7, -9, 4) uVtest1 = 0.5793 -0.7448 0.3310 >> uV2 = @(delX, delY, delZ) [delXdelYdelZ]/norm([delXdelYdelZ]); >> uVtest2 = uV2(7, -9, 4) uVtest2 = 0.5793 -0.7448 0.3310

  47. the Δ’s for this case Anonymous Fcn Unit Vector • Use uv2 to find uT = -0.4240 0.8480 0.3180 >> SpcAng = acosd(uT) SpcAng = 115.0873 32.0054 71.4580

  48. You can create anonymous functions having more than one input. For example, define the function Anonymous Fcns: Multi-Inputs >> pythag = @(x,y) sqrt(x.^2 + y.^2); >> c = pythag(13,17) c = 21.4009 >> pythag([3,7],[4,11]) ans = 5.0000 13.0384

More Related