MATLAB Functions Part I Greg Reese Ph D
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
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 3
Scripts 4
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 5
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) 6
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 7
Scripts BEFORE a=7 b=5 No other variables Script a = 3; c = 9; Note: a changed b unchanged c added AFTER a=3 b=5 c=9 8
Scripts Running a script can change the value of variables you have stored, or even erase the variables! 9
Scripts useful for: • Automating series of MATLAB commands, e. g. , ones you have to perform repeatedly from the command line • Initializing workspace 10
Scripts Try 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 any variables >> whos Name k rho theta Size 1 x 1 4 x 629 1 x 629 Bytes 8 20128 5032 Class double Attributes 11
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 12
Scripts Try It 1. Type – – initialize environment edit startup Put in name of directory on your machine Add the three lines cd some_directory hbar = 6. 6262 e-27 / ( 2*pi); mile. To. Km = 1. 6; 2. At the command line type startup 3. Verify that you're in the right directory and the two variables are set 13
Scripts Questions? 14
Using MATLAB Functions 15
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. 16
Functions Example exp(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) 17
Functions You can make complicated expressions by combining variables, functions, and arithmetic, e. g. , Math “*” means “×” 5*exp(-k*t)+17. 4*sin(2*pi*t/T) MATLAB Note how similar math and MATLAB are. 18
Functions Try It • Compute these • The sine of 90° is 1. Use the MATLAB function sin to compute the sine of 90°. Waz up? 19
Functions The MATLAB function sin is not doing what we expect. To get more information on a MATLAB function_name, type >> help function_name (Don’t include any parentheses. ) Try It Find out more about sin 20
Getting help The help information explains that the argument is in radians, not degrees. 21
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. 22
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”. 23
Getting help Example – what MATLAB function computes the inverse tangent? >> lookfor tangent produces 13 results of which three also say inverse – ATAN, ATAN 2, and ATAND 24
Getting help Questions? 25
Writing Functions 26
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. 27
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 28
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 Input Function a=5 b=? Calling Program Output a=? b=9 29
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 30
Writing Functions • What path does the baseball take? • How far does it go? • What's the best angle to throw it at? 31
Writing Functions Height y(t) V θ t Time y(t) = v sinθ t – ½ gt 2 • v is initial speed (velocity) • g is 32 feet/sec 2 • t is time • θ is throw angle 32
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 It Make an m-file to compute the baseball height at a given time and call the file height. m >> edit height. m Choose File menu, Save 33
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 34
Writing Functions function y = fname( v 1, v 2 ) 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 • “v 1”, “v 2” – input variable(s). Can be any variable name 35
Writing Functions function y = fname( v 1, v 2 ) • 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 36
Writing Functions Try It Make the first line of your function be function h = height( time ) 37
Writing Functions Pitcher #1 Greg (G-Dog) Reese Fastball = 40 mph* = 44 feet/sec * with strong tailwind 38
Writing Functions Try It Write 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 – ½ gt 2 Can be any name, but must be same name function h = height( time ) g = 32; speed = 44; angle = 70; h = speed*sind(angle)*time ? - 0. 5*g*time^2; 39
Writing Functions To 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^2 speed = 44; % feet/sec angle = 70; % degrees h = speed*sind(angle)*time - 0. 5*g*time^2; 40
Writing Functions Grayed-out “save” icon 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) 41
Writing Functions To 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 42
Writing Functions Often save result in a variable Try It >> h 1 >> h 2 >> h 1 = height(1) = 25. 3465 h 2 = height(2) = 18. 6930 h 1 = 25. 3465 43
Writing Functions Many functions require other functions to be passed to them. For example: • quad() – integration • fminbnd() – finding minimum • ezplot() – quick plot of function 44
Writing Functions To 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 45
Writing Functions Can see your function over range of values by using MATLAB function ezplot() To use: ez=easy ezplot( @my. Function, [ t 1 t 2 ] ) • Must include @ • my. Function can have any name but must accept one and only one argument • t 1 and t 2 are starting and ending plotted values of argument 46
Writing Functions Try It Plot 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; 47
Writing Functions V θ x Distance d that ball travels is d = v 2 sin(2θ) / g • v is initial speed (velocity) • g is 32 feet/sec 2 • θ is throw angle 48
Writing Functions Try It Write a function called distance that accepts a speed as an argument and returns the distance the ball was thrown. d = v 2 sin(2θ) / g function distance = distance( speed ) g = 32; % feet/sec^2 angle = 70; % degrees distance = ? ; speed^2 * sind(2*angle) / g; 49
Writing Functions Try It Store pitcher 1's speed (44 ft/sec) in a variable and find out how far he threw the ball >> speed 1 = 44; >> distance( speed 1 ) ans = 38. 8887 50
Writing Functions Pitcher #2 Nolan (The Ryan Express) Ryan Fastball = over 100 mph* = 147 feet/sec * even after he turned 40! 51
Writing Functions Try It Store pitcher 2's speed (147 ft/sec) in a variable and find out how far he threw the ball >> speed 2 = 147; >> distance( speed 2 ) ans = 434. 0624 52
Writing Functions Try It Make 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] ) 53
Writing Functions Try It The distance depends on both the velocity and the angle. Write a function called distance 2 that takes both those arguments and computes the distance d = v 2 sin(2θ)/g function distance = distance 2( speed, angle ) g = 32; % feet/sec^2 distance = speed^2 * sind(2*angle) / g; 54
Writing Functions Try It d = v 2 sin(2θ) / g Compute how far both pitchers throw the ball at a 20 o angle and at a 50 o angle >> distance 2(speed 1, 20) ans = 38. 8887 >> distance 2(speed 2, 20) ans = 434. 0624 >> distance 2(speed 1, 50) ans = 59. 5809 >> distance 2(speed 2, 50) ans = 665. 0222 55
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 distance 2( speed, angle) over the range of angles from 0 o to 90 o Problem: ezplot requires that the function passed to it have exactly one argument, but distance 2 has two arguments 56
Writing Functions One solution – write another function that accepts only the angle and has the speed stored in it. This function calls distance 2 function distance = distance 1( angle ) speed = 44; distance = distance 2( speed, angle ); >> ezplot( @distance 1, [0 90] ) 57
Writing Functions Drawbacks • Have to make another m-file • When speed changes, have to edit the m-file 58
Writing Functions Better solution Use an anonymous function to convert distance 2 to a function that accepts only one argument 59
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! 60
Writing Functions Try It "frozen" expression >> ezplot( @(angle)distance 2(speed 1, angle), [0 90] ) varies anonymous function 61
Writing Functions >> ezplot( @(angle)distance 2(speed 1, angle), [0 90] ) 62
Writing Functions Try It What angle should pitcher 1 throw the ball at to make it go as far as possible? 45 o 63
Writing Functions Try It Repeat for pitcher 2 45 o 64
Writing Functions Can 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 65
Writing Functions Try It Draw the angle-distance plots for both pitchers on the same graph >> >> hold on ezplot( @(angle)distance 2(speed 1, angle), [0 90] ) ezplot( @(angle)distance 2(speed 2, angle), [0 90] ) hold off 66
Writing Functions In other words… For the greatest distance throw the ball at a 45 o angle, regardless of how strong your arm is! 67
Writing Functions What 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 68
Writing Functions fminbnd finds the minimum of a singlevariable function on a specified interval >> x = fminbnd( @fun, x 1, x 2 ) • fun is a function that has exactly one argument • x 1 and x 2 are the starting and ending points of the interval 69
Writing Functions Tip fminbnd finds the minimum of a function fun(x). To find the maximum, use the negative of the function, i. e. , -fun(x) 70
Writing Functions Try It Use fminbnd to find the best angle for both pitchers >> fminbnd( @(angle) -distance 2(speed 1, angle), 0, 90 ) ans = 45 >> fminbnd( @(angle) -distance 2(speed 2, angle), 0, 90 ) ans =45 71
Writing Functions Questions? 72
The End 73
- Slides: 73