E7: INTRODUCTION TO COMPUTERE7: INTRODUCTION TO COMPUTER PROGRAMMING FOR SCIENTISTS AND ENGINEERSLecture Outline1.Anonymous functions 2Sub functions2.Sub functions 3.Nested FunctionsCopyright 2007 Horowitz Packard This work is licensed under the Creative Commons Attribution-ShareCopyright 2007, Horowitz, Packard. This work is licensed under the Creative Commons Attribution Share Alike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.Other types of functions Thfthtf ftiThere are four other types of functions–Anonymous functions•Define simple 1-line functions without creating an additional file.–Subfunctions•Multiple, separate functions within an m-file. One is the primaryfunction (what we already know), all others are subfunctions. –Nested functions•Functions defined within functions. Nested functions have their own isolated workspace, but rules for the scope of variables is slightly involved. –Private functions•Functions defined in a Privatefolder, visible only to functions in the folder containing the Privatefolder.We will focus on Anonymous, Sub andNested FunctionsAnonymous functions Create an anonymous functionusing syntax H = @(InputArgumentList) expressionHis the handle to the newly created anonymous function.Example:>>H1@( ) 3 7* i ( )Creates an anonymous function, H1is the function_handle to the function, which has one input argument.>> H1 = @(x) 3.7*sin(x);>> [H1(0) H1(pi/2) H1(pi)]ans =0 3.7000 0.0000>> H1H1 = @(x)3.7*sin(x)Anonymous functions • An anonymous functioncan use variables from the workspace were it is defined! Creates an anonymous function with handle H2. The c rrental e ofariableMissed in the definition>> M = 3.7;>> H2 = @(fred) M*sin(fred);>>[H2(0) H2(pi/2) H2(pi)]current value of variable is used in the definition.ans =03.70000.00000 3.7000 >> M = 4.7; % H2 remains unchanged>> [H2(0) H2(pi/2) H2(pi)]ans =03.70000.00000 3.7000 The value of the variable Mwhenthe anonymous function is created is used.
has intentionally blurred sections.
Sign up to view the full version.