MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology...
-
Upload
blanche-thomas -
Category
Documents
-
view
222 -
download
0
Transcript of MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology...
MATLAB
Functions – Part I
Greg Reese, Ph.D
Research Computing Support Group
Academic Technology Services
Miami University
September 2013
MATLAB Functions – Part I
© 2010-2013 Greg Reese. All rights reserved
2
3
M-files
M-file• Text file that holds MATLAB
commands or code • File ends in .m (for MATLAB)• Can hold a script or a function• Portable across platforms
Scripts
4
5
Scripts
A script is a sequence of MATLAB commands stored in an m-file• Type in file as you would enter on
command line – Don't type prompt (>>)
• Scripts are simplest m-files because they have no input or output passed to or from them
6
Scripts
To call a script is to execute (run) the commands in the script file• Call a script by typing its file's name
(the .m is optional)
A script can be called from:• The MATLAB command line• Another script• A function (to be discussed later)
7
Scripts
When you run a script from the command line• All variables created in the script remain in
your workspace• The script can access all variables that were
in the workspace before it ran
8
Scripts
Scripta = 3;c = 9;
BEFOREa = 7b = 5
No other variables
AFTERa = 3b = 5c = 9
Note: a changedb unchanged c added
9
Scripts
Running a script can change the value of variables you have stored, or even erase the variables!
10
Scripts
Scripts useful for:• Automating series of MATLAB commands,
e.g., ones you have to perform repeatedly from the command line
• Initializing workspace
11
ScriptsTry It – automating commands
1. Remove all variables in your workspace by typing clear all and confirm by typing whos
2. Download the script petals.m and run it
3. Type whos to see if there are any variables
>> whos Name Size Bytes Class Attributes k 1x1 8 double rho 4x629 20128 double theta 1x629 5032 double
12
Scripts
MATLAB runs startup.m when it starts. Put commands in file to set up your environment• Set working directory• Store often-used variables• Add directory of group functions to
MATLAB path
13
Scripts
Try It – initialize environment
1. Type edit startup– Add the three lines
cd some_directoryhbar = 6.6262e-27 / ( 2*pi);mileToKm = 1.6;
2. At the command line type startup3. Verify that you're in the right directory
and the two variables are set
Put in name of directory on your machine
14
Scripts
Questions?
Using MATLAB Functions
15
16
Functions
You’re likely to want to compute functions of a variable, e.g.,
MATLAB has a large number of standard mathematical functions. To compute the function of a variable write the function name followed by the variable in parentheses.
x kxe )ln(x
17
Functions
Exampleexp(x)
sqrt(x)• Usually store result in a variable,
e.g., root_x=sqrt(x)• Can pass constants too,
e.g., root_2=sqrt(2)
xe
x
18
Functions
You can make complicated expressions by combining variables, functions, and arithmetic, e.g.,
5*exp(-k*t)+17.4*sin(2*pi*t/T)
Note how similar math and MATLAB are.
Tte kt 2sin4.175 Math
MATLAB
“*” means “×”
19
Functions
Try It• Compute these
• The sine of 90° is 1. Use the MATLAB function sin to compute the sine of 90°.
Waz up?
2 4 8for2.0 xxe
20
Functions
The MATLAB function sin is not doing what we expect. To get more information on a MATLAB function function_name, type
>> help function_name(Don’t include any parentheses.)
Try ItFind out more about sin
21
Getting help
The help information explains that the argument is in radians, not degrees.
22
Getting help
The help information often has links to related functions. Type help sin again and click on the link sind. It tells you that sind computes the sine of an argument that is in degrees.
23
Getting help
What if you don’t know the MATLAB name of a mathematical function? Use
>> lookfor word
to search in the basic help information for “word”.
24
Getting help
Example – what MATLAB function computes the inverse tangent?
>> lookfor tangent
produces 13 results of which three also say inverse – ATAN, ATAN2, and ATAND
25
Getting help
Questions?
Writing Functions
26
27
Writing Functions
A function is a MATLAB program that can accept inputs and produce outputs. Some functions don't take any inputs and/or produce outputs.
A function is called or executed (run) by another program or function. That program can pass it input and receive the function's output.
28
Writing Functions
Why use functions?• Use same code in more than one place in
program• Reuse code by calling in different programs• Make debugging easier by putting all of one
kind of functionality in one place
29
Writing Functions
Think of a function as a black box. • Calling program can't see (access) any of the variables inside the function• Function can't see any variables in the calling program
Function a = 5 b = ?Input Output
Calling Program a = ? b = 9
30
Writing Functions
The code for a function is in an m-file. You can make the file in any text editor but it's easiest to do it with the MATLAB editor. To do this, at the command prompt type edit followed optionally by a filename not in quotes
• if file in current directory, MATLAB opens it• if not in current directory, MATLAB creates it
31
Writing Functions
• What path does the baseball take?• How far does it go?• What's the best angle to throw it at?
32
Writing Functions
y(t) = v sinθ t – ½ gt2
• v is initial speed (velocity)• g is 32 feet/sec2
• t is time• θ is throw angle
t
y(t)
Time
Hei
ght
θ
V
33
Writing Functions
As soon as you make an m-file, give it a name (if needed) and save it. Do this by choosing “Save” or “Save as” under the file menu.
Try ItMake an m-file to compute the baseball height at a given time and call the file height.m>> edit height.mChoose File menu, Save
34
Writing Functions
Function names• Must begin with a letter• Can contain any letters, numbers,
or an underscore• Name of file that contains function
should be function name with “.m” appended
– Example: the function compute_area should be in the file called compute_area.m
35
Writing Functionsfunction y = fname( v1, v2 )
First line of function is called the function line• “function” – keyword that tells MATLAB function
starts with this line. Must be the word “function”• “y” – output variable(s). Can be any variable name• “fname” – any function name• “v1”, “v2” – input variable(s). Can be any variable name
36
Writing Functions
function y = fname( v1, v2 )• Function ends when:
1. Another function line appears
2. An end-statement that matches the function line appears
3. There's no more code in file
• If function has outputs, must declare variables with output variable names and compute their values before function ends
37
Writing Functions
Try ItMake the first line of your function be
function h = height( time )
38
Writing Functions Pitcher #1
Greg (G-Dog) Reese
Fastball = 40 mph*
= 44 feet/sec
* with strong tailwind
function h = height( time )g = 32;speed = 44;angle = 70;h = ?
39
Writing FunctionsTry ItWrite a function called height that accepts a time as an argument and returns the height at that time. Use the MATLAB function sind() to calculate the sine of an angle in degrees y(t) = v sinθ t – ½ gt2
function h = height( time )g = 32;speed = 44;angle = 70;h = speed*sind(angle)*time - 0.5*g*time^2;
Can be any name, but must be same name
40
Writing FunctionsTo make the code clearer you can write comments, text that MATLAB ignores. If MATLAB sees a percent sign (%) it ignores the sign and everything after it on the rest of the line
function h = height( time )g = 32; % feet/sec^2speed = 44; % feet/secangle = 70; % degreesh = speed*sind(angle)*time - 0.5*g*time^2;
41
Writing Functions
CAREFUL! You MUST save the file for any changes you made to go into effect. If you've fixed an error but your function still doesn't seem to work, make sure you saved the file.
TIP
If all changes to a file have been saved, the “save-icon”, a diskette, will be disabled (grayed-out)
Grayed-out “save” icon
42
Writing FunctionsTo call a function type its name followed by the arguments in parentheses. If no arguments, can omit parentheses
Try It>> height(1)ans = 25.3465>> height(2.5)ans = 3.3662
43
Writing FunctionsOften save result in a variable
Try It>> h1 = height(1)h1 = 25.3465>> h2 = height(2)h2 = 18.6930>> h1h1 = 25.3465
44
Writing FunctionsMany functions require other functions to be passed to them. For example:• quad() – integration• fminbnd() – finding minimum• ezplot() – quick plot of function
45
Writing FunctionsTo pass one function to another, use a function handle
Function handle– MATLAB data type that contains all info
needed to evaluate function– Make a function handle by putting the @
character in front of the function name
46
Writing FunctionsCan see your function over range of values by using MATLAB function ezplot()
To use:
ezplot( @myFunction, [ t1 t2 ] )• Must include @• myFunction can have any name but must accept one and only one argument• t1 and t2 are starting and ending plotted values of argument
ez=easy
47
Writing FunctionsTry ItPlot the baseball's height from when it's thrown to 2½ seconds later
>> ezplot( @height, [0 2.5] )Ignore the message Warning: Function failed to evaluate on array inputs;
48
Writing Functions
Distance d that ball travels is
d = v2 sin(2θ) / g• v is initial speed (velocity)• g is 32 feet/sec2
• θ is throw angle
xDistance
θ
V
function distance = distance( speed )g = 32; % feet/sec^2angle = 70; % degreesdistance = ?;
function distance = distance( speed )g = 32; % feet/sec^2angle = 70; % degreesdistance = speed^2 * sind(2*angle) / g;
49
Writing FunctionsTry ItWrite a function called distance that accepts a speed as an argument and returns the distance the ball was thrown.
d = v2 sin(2θ) / g
>> speed1 = 44;>> distance( speed1 )ans = 38.8887
50
Writing Functions
Try ItStore pitcher 1's speed (44 ft/sec) in a variable and find out how far he threw the ball
51
Writing FunctionsPitcher #2
Nolan (The Ryan Express) Ryan
Fastball = over 100 mph* = 147 feet/sec
* even after he turned 40!
>> speed2 = 147;>> distance( speed2 )ans = 434.0624
52
Writing Functions
Try ItStore pitcher 2's speed (147 ft/sec) in a variable and find out how far he threw the ball
53
Writing FunctionsTry ItMake a graph of how the distance the ball flies depends on the speed at which it's thrown. Plot the results from 40 to 140 feet/sec>> ezplot( @distance, [40 140] )
function distance = distance2( speed, angle )g = 32; % feet/sec^2distance = speed^2 * sind(2*angle) / g;
54
Writing Functions
Try ItThe distance depends on both the velocity and the angle. Write a function called distance2 that takes both those arguments and computes the distance d = v2 sin(2θ)/g
>> distance2(speed1,20)ans = 38.8887>> distance2(speed2,20)ans = 434.0624>> distance2(speed1,50)ans = 59.5809>> distance2(speed2,50)ans = 665.0222
55
Writing Functions
Try It d = v2 sin(2θ) / g
Compute how far both pitchers throw the ball at a 20o angle and at a 50o
angle
56
Writing Functions
Want to find "best" angle, i.e., angle that makes the ball go the farthest. One way to do this is to plot
distance2( speed, angle)
over the range of angles from 0o to 90o
Problem: ezplot requires that the function passed to it have exactly one argument, but distance2 has two arguments
57
Writing Functions
One solution – write another function that accepts only the angle and has the speed stored in it. This function calls distance2
function distance = distance1( angle )speed = 44;distance = distance2( speed, angle );
>> ezplot( @distance1, [0 90] )
58
Writing Functions
Drawbacks• Have to make another m-file• When speed changes, have to edit the
m-file
59
Writing Functions
Better solution
Use an anonymous function to convert distance2 to a function that accepts only one argument
60
Writing Functions
Anonymous function – a quick way to write a simple function without having to make an m-file
@(arguments) expression• arguments – list of arguments separated
by commas• expression – a single MATLAB
expression. Can be a call of another function!
Try It
61
Writing Functions
>> ezplot( @(angle)distance2(speed1,angle),[0 90] )
anonymous function
expression
"frozen"
varies
62
Writing Functions
>> ezplot( @(angle)distance2(speed1,angle),[0 90] )
63
Writing FunctionsTry ItWhat angle should pitcher 1 throw the ball at to make it go as far as possible?
45o
64
Writing FunctionsTry ItRepeat for pitcher2
45o
65
Writing FunctionsCan plot more than one data set on a graph. To do so:
1. Type the hold on command
2. Type the various ezplot calls
3. Type the hold off command
66
Writing Functions
Try ItDraw the angle-distance plots for both pitchers on the same graph
>> hold on>> ezplot( @(angle)distance2(speed1,angle),[0 90] )>> ezplot( @(angle)distance2(speed2,angle),[0 90] )>> hold off
67
Writing FunctionsIn other words…For the greatest distance throw the ball at a 45o angle, regardless of how strong your arm is!
68
Writing FunctionsWhat angle should you throw the ball at to make it go as far as possible?
Another solution – use a MATLAB optimization function to find the angle that maximizes the distance
69
Writing Functionsfminbnd finds the minimum of a single-variable function on a specified interval
>> x = fminbnd( @fun, x1, x2 )• fun is a function that has exactly one argument• x1 and x2 are the starting and ending points of the interval
70
Writing Functions
Tipfminbnd finds the minimum of a function fun(x). To find the maximum, use the negative of the function, i.e., -fun(x)
71
Writing Functions
Try ItUse fminbnd to find the best angle for both pitchers
>> fminbnd( @(angle) -distance2(speed1,angle),0,90 )ans = 45>> fminbnd( @(angle) -distance2(speed2,angle),0,90 )ans =45
72
Writing Functions
Questions?
73
The End