MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology...

73
MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013

Transcript of MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology...

Page 1: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

MATLAB

Functions – Part I

Greg Reese, Ph.D

Research Computing Support Group

Academic Technology Services

Miami University

September 2013

Page 2: 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

Page 3: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 4: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Scripts

4

Page 5: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 6: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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)

Page 7: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 8: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

8

Scripts

Scripta = 3;c = 9;

BEFOREa = 7b = 5

No other variables

AFTERa = 3b = 5c = 9

Note: a changedb unchanged c added

Page 9: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

9

Scripts

Running a script can change the value of variables you have stored, or even erase the variables!

Page 10: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

10

Scripts

Scripts useful for:• Automating series of MATLAB commands,

e.g., ones you have to perform repeatedly from the command line

• Initializing workspace

Page 11: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 12: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 13: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 14: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

14

Scripts

Questions?

Page 15: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Using MATLAB Functions

15

Page 16: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 17: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 18: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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 “×”

Page 19: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 20: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 21: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

21

Getting help

The help information explains that the argument is in radians, not degrees.

Page 22: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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.

Page 23: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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”.

Page 24: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 25: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

25

Getting help

Questions?

Page 26: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Writing Functions

26

Page 27: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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.

Page 28: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 29: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 30: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 31: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

31

Writing Functions

• What path does the baseball take?• How far does it go?• What's the best angle to throw it at?

Page 32: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 33: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 34: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 35: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 36: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 37: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

37

Writing Functions

Try ItMake the first line of your function be

function h = height( time )

Page 38: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

38

Writing Functions Pitcher #1

Greg (G-Dog) Reese

Fastball = 40 mph*

= 44 feet/sec

* with strong tailwind

Page 39: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 40: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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;

Page 41: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 42: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 43: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 44: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

44

Writing FunctionsMany functions require other functions to be passed to them. For example:• quad() – integration• fminbnd() – finding minimum• ezplot() – quick plot of function

Page 45: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 46: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 47: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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;

Page 48: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 49: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 50: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

>> 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

Page 51: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

51

Writing FunctionsPitcher #2

Nolan (The Ryan Express) Ryan

Fastball = over 100 mph* = 147 feet/sec

* even after he turned 40!

Page 52: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

>> 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

Page 53: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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] )

Page 54: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 55: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

>> 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

Page 56: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 57: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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] )

Page 58: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

58

Writing Functions

Drawbacks• Have to make another m-file• When speed changes, have to edit the

m-file

Page 59: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

59

Writing Functions

Better solution

Use an anonymous function to convert distance2 to a function that accepts only one argument

Page 60: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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!

Page 61: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

Try It

61

Writing Functions

>> ezplot( @(angle)distance2(speed1,angle),[0 90] )

anonymous function

expression

"frozen"

varies

Page 62: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

62

Writing Functions

>> ezplot( @(angle)distance2(speed1,angle),[0 90] )

Page 63: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

63

Writing FunctionsTry ItWhat angle should pitcher 1 throw the ball at to make it go as far as possible?

45o

Page 64: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

64

Writing FunctionsTry ItRepeat for pitcher2

45o

Page 65: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 66: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 67: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

67

Writing FunctionsIn other words…For the greatest distance throw the ball at a 45o angle, regardless of how strong your arm is!

Page 68: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 69: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 70: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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)

Page 71: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

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

Page 72: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

72

Writing Functions

Questions?

Page 73: MATLAB Functions – Part I Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.

73

The End