E7: INTRODUCTION TO COMPUTER
E7: INTRODUCTION TO COMPUTER
PROGRAMMING FOR SCIENTISTS AND
ENGINEERS
Lecture Outline
1.
Anonymous functions
2
Sub functions
2.
Sub functions
3.
Nested Functions
Copyright 2007 Horowitz Packard This work is licensed under the Creative Commons Attribution-Share
Copyright 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
Th
f
th
t
f f
ti
There 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 primary
function (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
Private
folder, visible only to functions in
the folder containing the
Private
folder.
We will focus on
Anonymous, Sub
and
Nested Functions
Anonymous functions
Create an
anonymous function
using syntax
H = @(InputArgumentList) expression
H
is the handle to the newly created anonymous function.
Example:
>>
H1
@( ) 3 7* i ( )
Creates an anonymous function,
H1
is 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
>> H1
H1 =
@(x)3.7*sin(x)
Anonymous functions
• An
anonymous function
can use variables from the
workspace were it is defined!
Creates an anonymous function with handle
H2.
The
c rrent
al e of
ariable
M
is
sed 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 =
0
3.7000
0.0000
0
3.7000
>> M = 4.7;
% H2 remains unchanged
>> [H2(0) H2(pi/2) H2(pi)]
ans =
0
3.7000
0.0000
0
3.7000
The value of the variable
M
when
the anonymous
function is created is used.

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*