ENGR-25_Lec-07_Functions

advertisement
Engr/Math/Physics 25
Chp3 MATLAB
Functions: Part3
Bruce Mayer, PE
Licensed Electrical & Mechanical Engineer
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
Function Handles
 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
>> 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, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
6
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
>> ln_handle = @log;
>>
gen_plot(ln_handle,1:99)
• Plot over 1→99
Engineering/Math/Physics 25: Computational Methods
7
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Function Handles cont
 Can Pass a Function with @ sign handle
>> gen_plot(@sech,0:.02:10)
Engineering/Math/Physics 25: Computational Methods
8
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Calling Functions

There are four ways to invoke, or “call,” a
function into action. These are:
1. As a character string identifying the
appropriate function .m-file
2. As a function handle
3. As an “inline” function object
4. 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
Engineering/Math/Physics 25: Computational Methods
9
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
parab.m Graphed
25
xplt = linspace(-5,5);
yplt = parab(xplt)
plot(xplt,yplt)
grid
xlabel('x')
ylabel('parab(x)')
20
parab(x)
15
10
5
0
-5
-5
-4
-3
-2
Engineering/Math/Physics 25: Computational Methods
10
-1
0
x
1
2
3
4
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
5
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
Engineering/Math/Physics 25: Computational Methods
11
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
12
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
13
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Calling Functions cont

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
Engineering/Math/Physics 25: Computational Methods
14
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Types of User Defined Fcns

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.
Engineering/Math/Physics 25: Computational Methods
15
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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.
Engineering/Math/Physics 25: Computational Methods
16
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
17
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Types of User Defined Fcns

SUBFUNCTIONS are placed in the primary
function and are called by the primary fcn
•

NESTED functions are functions defined
within another function.
•

You can use multiple functions within a
single primary function m-file
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
Engineering/Math/Physics 25: Computational Methods
18
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Types of User Defined Fcns

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.
Engineering/Math/Physics 25: Computational Methods
19
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.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.
Engineering/Math/Physics 25: Computational Methods
20
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.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, valid MATLAB
expression.
Engineering/Math/Physics 25: Computational Methods
21
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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ˆ 
 y B  y A  ˆj 

z B  z A k
Engineering/Math/Physics 25: Computational Methods
22
 xB , y B , z B 
û
x A , y A , z A 
 Or using Δ Notation
AB  xABiˆ  y AB ˆj  z AB zˆ
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Fcn  Unit Vector
 Next Calculate the
Geometric Length,
AB, of The Direction
Vector AB using
Pythagorus
AB  AB  LAB
 x
2
AB
 y
2
AB
 z
2
AB
 Now AB has the
same Direction as u,
but a different length
Engineering/Math/Physics 25: Computational Methods
23
 xB , y B , z B 
û
x A , y A , z A 
 “Normalizing” AB to
its Length will
produce a vector of
unit Length; i.e., u
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Fcn  Unit Vector
 Normalize AB to
Produce û
AB AB
uˆ 

LAB AB

xiˆ  yˆj  zkˆ
 xB , y B , z B 
û
x A , y A , z A 
2
2
2
x AB
 y AB
 z AB
 the Δ’s for this case  Create MATLAB
x AB  40m y AB  80m Anonymous Fcn:
uV(Δx, Δy, Δz)
z AB  30m
Engineering/Math/Physics 25: Computational Methods
24
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Fcn  Unit Vector
 Write Anon Fcn uV
completely in the
COMMAND Window
 Test using
conditions Given at
Right
 xB , y B , z B 
û
x A , y A , z A 
• Also find Space Angles
by acosd(uAB)
Engineering/Math/Physics 25: Computational Methods
25
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
26
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Function in fzero
 Solve the
Transcendental
Equation
7 cos x  ln x  1
 Collect Terms on
One Side, 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
>> 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
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
@Cos_ln (x) Graphed: 0-2.5π
8
>> 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
6
4
2
v
0
-2
-4
-6
-8
-10
0
1
2
3
Engineering/Math/Physics 25: Computational Methods
28
4
u
5
6
7
8
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
ANONYMOUS Function example

Build, completely in the Command Window,
1n
a function that returns the
nth Root of a Scalar Base
zB
>> 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
Engineering/Math/Physics 25: Computational Methods
29
1.4678
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Functions cont

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]
>>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)
Engineering/Math/Physics 25: Computational Methods
30
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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.
Engineering/Math/Physics 25: Computational Methods
31
>>f = @(x) x.^3;
>>g = @(x) 5*sin(x);
>>h = @(x) g(f(x));
>>h(2)
ans =
4.9468
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
32
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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.
>> A = 3; B = 7;
•
If the values of A or B
are changed after the
handle is created,
their values associated
with the handle do
NOT change.
Engineering/Math/Physics 25: Computational Methods
33
>> plane = @(x,y)
A*x + B*y
>> P1 = plane (1,2)
P1 =
17
>> A = 9; B = 14;
>> P2 = plane (1,2)
P2 =
17
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
SubFunctions

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
Engineering/Math/Physics 25: Computational Methods
34
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
SubFunctions cont

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.
Engineering/Math/Physics 25: Computational Methods
35
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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)
% Calculate average.
a = sum(v)/n;
% Subfunction
function m = median(v, n)
% 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
% Subfunction
Engineering/Math/Physics 25: Computational Methods
36
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
SubFunction Example Results
>> w = [12:0.37:209];
>> z = log(w).*(cos(w)).^2;
>> [zavg, zmed] = newstatsSF(z)
zavg =
2.2590
zmed =
2.1168
Engineering/Math/Physics 25: Computational Methods
37
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
38
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Function-Call Precedence cont

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.
Engineering/Math/Physics 25: Computational Methods
39
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
SubFunction Example

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.
function r = residual_x(a)
r = a - mean(a);
%
function w = mean(z)
w = sqrt(sum(z.^2))/length(z);
Engineering/Math/Physics 25: Computational Methods
40
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
41
Note:
RMS mean = 2.8284
>> r2 = v - mean(v)
r2 =
4
-4
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
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
Engineering/Math/Physics 25: Computational Methods
42
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
All Done for Today
Some Root
Mean Square
Calculations
Engineering/Math/Physics 25: Computational Methods
43
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Engr/Math/Physics 25
Appendix
Bruce Mayer, PE
Licensed Electrical & Mechanical Engineer
BMayer@ChabotCollege.edu
f x   2 x  7 x  9 x  6
3
2
Engineering/Math/Physics 25: Computational Methods
44
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
@Cos_ln (x) Graphed
8
6
4
l
y = cos n(x)
2
0
-2
cos_ln = @(x) 7*cos(x) - log(x+1)
xplt = linspace(0,3);
yplt = cos_ln(xplt);
-6 plot(xplt,yplt)
grid
-8 xlabel('x')
ylabel('y = cos_ln(x)')
-4
-10
0
0.5
1
Engineering/Math/Physics 25: Computational Methods
45
1.5
x
2
2.5
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
3
Anonymous Fcn  Unit Vector
>> uV1 = @(delX, delY, delZ) [delX delY
delZ]/(sqrt(sum([delX delY delZ].*[delX delY
delZ])));
>> uVtest1 = uV1(7, -9, 4)
uVtest1 =
0.5793
-0.7448
0.3310
>> uV2 = @(delX, delY, delZ) [delX delY
delZ]/norm([delX delY delZ]);
>> uVtest2 = uV2(7, -9, 4)
uVtest2 =
0.5793
-0.7448
0.3310
Engineering/Math/Physics 25: Computational Methods
46
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Fcn  Unit Vector
 the Δ’s for this case
x AB  40m y AB  80m
z AB  30m
û
 Use uv2 to find
uT =
-0.4240
0.8480
>> SpcAng = acosd(uT)
SpcAng =
115.0873
32.0054
Engineering/Math/Physics 25: Computational Methods
47
0.3180
71.4580
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Anonymous Fcns: Multi-Inputs

You can create anonymous functions having
more than one input. For
pythag  x 2  y 2
example, define the function
>> 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
Engineering/Math/Physics 25: Computational Methods
48
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Functions-3.ppt
Download