Download presentation
Presentation is loading. Please wait.
Published byBlanche Thomas Modified over 9 years ago
1
MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013
2
MATLAB Functions – Part I © 2010-2013 Greg Reese. All rights reserved 2
3
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
4
Scripts 4
5
5 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
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
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
8 Scripts Script a = 3; c = 9; BEFORE a = 7 b = 5 No other variables AFTER a = 3 b = 5 c = 9 Note: a changed b unchanged c added
9
9 Scripts Running a script can change the value of variables you have stored, or even erase the variables!
10
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
11 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 are any variables >> whos Name Size Bytes Class Attributes k 1x1 8 double rho 4x629 20128 double theta 1x629 5032 double
12
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
13 Scripts Try It – initialize environment 1.Type edit startup –Add the three lines cd some_directory hbar = 6.6262e-27 / ( 2*pi); mileToKm = 1.6; 2.At the command line type startup 3.Verify that you're in the right directory and the two variables are set Put in name of directory on your machine
14
14 Scripts Questions?
15
Using MATLAB Functions 15
16
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.
17
17 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)
18
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. Math MATLAB “ * ” means “×”
19
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?
20
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 It Find out more about sin
21
21 Getting help The help information explains that the argument is in radians, not degrees.
22
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
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
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
25 Getting help Questions?
26
Writing Functions 26
27
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
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
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 = ? InputOutput Calling Program a = ? b = 9
30
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
31 Writing Functions What path does the baseball take? How far does it go? What's the best angle to throw it at?
32
32 Writing Functions y(t) = v sinθ t – ½ gt 2 v is initial speed (velocity) g is 32 feet/sec 2 t is time θ is throw angle t y(t ) Time Height θ V
33
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 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
34
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
35 Writing Functions function 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
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
37 Writing Functions Try It Make the first line of your function be function h = height( time )
38
38 Writing Functions Pitcher #1 Greg (G-Dog) Reese Fastball = 40 mph * = 44 feet/sec * with strong tailwind
39
function h = height( time ) g = 32; speed = 44; angle = 70; h = ? 39 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 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
40 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;
41
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
42 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
43
43 Writing Functions Often save result in a variable Try It >> h1 = height(1) h1 = 25.3465 >> h2 = height(2) h2 = 18.6930 >> h1 h1 = 25.3465
44
44 Writing Functions Many functions require other functions to be passed to them. For example: quad() – integration fminbnd() – finding minimum ezplot() – quick plot of function
45
45 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
46
46 Writing Functions Can 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
47 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;
48
48 Writing Functions 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 x Distance θ V
49
function distance = distance( speed ) g = 32; % feet/sec^2 angle = 70; % degrees distance = ?; function distance = distance( speed ) g = 32; % feet/sec^2 angle = 70; % degrees distance = speed^2 * sind(2*angle) / g; 49 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
50
>> speed1 = 44; >> distance( speed1 ) ans = 38.8887 50 Writing Functions Try It Store pitcher 1's speed (44 ft/sec) in a variable and find out how far he threw the ball
51
51 Writing Functions Pitcher #2 Nolan (The Ryan Express) Ryan Fastball = over 100 mph * = 147 feet/sec * even after he turned 40!
52
>> speed2 = 147; >> distance( speed2 ) ans = 434.0624 52 Writing Functions Try It Store pitcher 2's speed (147 ft/sec) in a variable and find out how far he threw the ball
53
53 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] )
54
function distance = distance2( speed, angle ) g = 32; % feet/sec^2 distance = speed^2 * sind(2*angle) / g; 54 Writing Functions Try It The distance depends on both the velocity and the angle. Write a function called distance2 that takes both those arguments and computes the distance d = v 2 sin(2θ)/g
55
>> 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 = v 2 sin(2θ) / g Compute how far both pitchers throw the ball at a 20 o angle and at a 50 o angle
56
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 0 o to 90 o Problem: ezplot requires that the function passed to it have exactly one argument, but distance2 has two arguments
57
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
58 Writing Functions Drawbacks Have to make another m-file When speed changes, have to edit the m-file
59
59 Writing Functions Better solution Use an anonymous function to convert distance2 to a function that accepts only one argument
60
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!
61
Try It 61 Writing Functions >> ezplot( @(angle)distance2(speed1,angle),[0 90] ) anonymous function expression "frozen" varies
62
62 Writing Functions >> ezplot( @(angle)distance2(speed1,angle),[0 90] )
63
63 Writing Functions Try It What angle should pitcher 1 throw the ball at to make it go as far as possible? 45 o
64
64 Writing Functions Try It Repeat for pitcher2 45 o
65
65 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
66
66 Writing Functions Try It Draw 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
67 Writing Functions In other words… For the greatest distance throw the ball at a 45 o angle, regardless of how strong your arm is!
68
68 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
69
69 Writing Functions fminbnd 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
70 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)
71
71 Writing Functions Try It Use 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
72 Writing Functions Questions?
73
73 The End
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.