109
Introduction to MATLAB for MTH 432/532 – Optimization Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University January 2007

Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

Introduction to MATLAB for

MTH 432/532 – Optimization

Greg Reese, Ph.DResearch Computing Support GroupAcademic Technology ServicesMiami University

January 2007

Page 2: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

2

Workshop informationTo get a copy of this presentation, go to

www.muohio.edu/researchcomputing

follow the links to the Tutorials page,

and download the file entitled

Introduction to MATLAB for MTH 432

Page 3: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

3

Workshop informationYou may also want a copy of

Introduction to MATLAB for MTH 453

available at the same site. It has material not covered here.

Page 4: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

4

Workshop informationFormat• Interactive presentation with hands-

on use of MATLABRequirements• NoneDuration• Two hoursStyle• Informal – ask questions any time

you want!

Page 5: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

5

Outline• Overview of MATLAB• MATLAB environment

– Getting started– Arithmetic– Variables, mathematical functions– Getting help on MATLAB

Page 6: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

6

Outline• Vector (a collection of numbers)• Plotting

– Make quick plots of functions specified in notational form

– Use plots in other programs

Page 7: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

7

OutlineSpecial topics for optimization• Writing MATLAB functions• Using custom functions with MATLAB• Optimization routines in MATLAB

optimization toolbox

Page 8: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

8

MATLAB• Stands for MATrix LABoratory

– Originally designed for efficient computation with matrices

• Language and environment for technical computing

Overview

Page 9: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

9

OverviewMathematical capabilities• LARGE number of math

computations– Simple

• Arithmetic, trigonometry, complex numbers– Fancy

• Matrix inverses and eigenvalues• Bessel functions• Fourier transforms

Don’t panic!

Page 10: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

10

OverviewGraphics• Easily plot data• Easily plot functions• Annotate graphs• 2D and 3D data visualization• Image processing

Page 11: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

11

Getting StartedDouble-click on MATLAB icon on desktop. Close all windows except one with the prompt (>>). That window is called the command window.

Most of your work takes place in the command window. After you press ENTER you get the answer and get another prompt.

Page 12: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

12

Getting StartedNOTEAfter typing a MATLAB command you always press ENTER to activate it. Won’t show that anymore

Page 13: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

13

Getting Started

Try It

• To learn what version of MATLAB you have run the ver command

• To find today’s date enter date

Page 14: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

14

TerminologyMATLAB designed to work on matrices• matrix – a rectangular array of

numbers

• vector – a matrix with only one row or columnrow vector column vector

• scalar – a matrix with only one row and column, i.e., a number

1.3 2

-7 -3.4

9 8

1 7 -4.3

0.05

-33.7

100

99

-23.8 1009.76

Page 15: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

15

Variablesvariable – a name that represents a MATLAB object such as a scalar, vector or matrix.

You can change (vary) the value of a variable

Page 16: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

16

VariablesVariable name• Must start with a letter• Have any number of letters, digits,

or underscores• No spaces allowed (use an

underscore instead)• Only first 31 characters of a name

are important to MATLAB

Page 17: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

17

VariablesMATLAB is case-sensitive, i.e., it

distinguishes between upper and lower case letters in a variable name

• BOB, bob, and Bob count as different names

Tip - Don’t purposely make names that differ only in capitalization. You, not MATLAB, will get confused!

Page 18: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

18

VariablesTo make a variable just type its name

followed by an equals sign and a value, e.g., x = 5

To see the value of a variable just type its name at the command prompt.

• If there’s no variable with that name (for example, “y”), MATLAB will say??? Undefined function or variable 'y'.

Spaces are optional

Page 19: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

19

Variables

Tip – variable name should have meaning

Example – “Number of students”might be num_students or numStudents, but not x or n

Page 20: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

20

Variables

Try It

• Make a variable to represent the number of students in a class and set it to 30

• Make a variable to represent the year you were born and set it

• Display the values of the two variables

• Display the value of the variable qq

Page 21: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

21

NumbersNumbers• Can have decimal point, leading

plus or minus sign, e.g., 3 4.7 -5 +5 .01 0.01 0.010

• Scientific notation – use “e” to specify power of ten, e.g., 6.02 × 1023 is 6.02e237.02 × 10-34 is 7.02e-34

Page 22: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

22

NumbersNumbers• Internally variables have precision of

about 16 decimal digits and range from about 10-308 to 10+308

(good enough for government work!)

Page 23: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

23

Variables

Try It

Make variables to represent the following constants and set them to the indicated values

Speed of light 3.00×108

Plank’s constant 6.63×10-34

Avogadro’s number 6.02×1023

Degrees in a circle 360Bottles of beer 99

Page 24: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

24

ArithmeticMATLAB• Has normal arithmetic operations• Has some that are not as familiar• Use standard evaluation order

– 3 × 5 + 7 = 22 (multiply first, then add)• Can use parentheses in usual way

to change evaluation order– 3 × ( 5 + 7 ) = 36

Page 25: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

25

ArithmeticSymbol Operation

+ Addition

- Subtraction

* Multiplication

/ Division

^ Power

Arithmetic on scalars

Page 26: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

26

ArithmeticYou can use MATLAB as a fancy

calculator. For example, to evaluate 4x3 – 3x + 7 at x = 3.5 type4*3.5^3 – 3*3.5 + 7

Page 27: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

27

ArithmeticMATLAB has π as a built-in constant. Type

pi to get itTry It

Compute the• Area of a circle of radius 3: π ×32

• Area of circle, diameter 6: π ×(6/2)2

• Volume of cone (1/3)× π ×h×r2

compute at r = 2.78 and h = 9.34

A = 28.27 V = 75.59

Page 28: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

28

VariablesIt’s more common to do arithmetic on variables. Do it the same way as with constants. For example:

>> radius = 5radius = 5>> area = pi * radius ^ 2area = 78.5398

Page 29: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

29

Variables

Try It

• Make variables for the length and width of a rectangle and set them to 9 and 5. Compute the area of the rectangle using the variables (45).

• Now use the variables to compute the perimeter.

Page 30: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

30

VariablesThe equals sign (=) means “assign to” or “set to”. It doesn’t mean, as in math, that the left side is equal to the right. You can have the same variable on both sides of the equal sign. For example:>> x = 7x = 7>> x = x + 6x = 13>> x = 2 * xx = 26

Page 31: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

31

Variables

Tip

• Left and right arrow keys move within current command line

• Up and down arrow keys move among command lines

• Type letters then use up and down arrow keys to move among command lines starting with those letters

Page 32: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

32

VariablesTry It

• Type r=5 and ENTER• Type pi*r^2 for areaTo compute area for new radius1. Press up arrow twice2. Use backspace key to delete the 53. Type 10 and ENTER4. Press up arrow key twice5. Press ENTER for area of new radius

Page 33: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

33

Variables

Tip

It can get tedious seeing intermediate values such as the radius and the height. To suppress the output of a command, put a semicolon at the end of the line, e.g., r=5;

Page 34: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

34

Managing Variables• To display the value of a variable x:

>> x

• If that variable doesn’t exist, MATLAB says

??? Undefined function or variable 'rr'.

Page 35: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

35

FunctionsYou’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 36: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

36

FunctionsExample

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)

xe

x

Page 37: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

37

FunctionsYou 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 38: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

38

FunctionsTry It

• Compute these

2 4 8for2.0 =− xxe

Remember to put a multiplication between the 2

and the x

Page 39: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

39

Getting HelpTo get help on a MATLAB command, type “help” followed by space and the command name, e.g.,

>> help fprintf

Try It

Page 40: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

40

Getting HelpMATLAB will display information on what the command does, what its inputs and outputs are, what algorithms it uses, etc. It also displays links to related commands.

Page 41: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

41

Getting helpQuestions?• Variables• Arithmetic• Help

Page 42: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

42

VectorsA vector is a one-dimensional matrix. It is a single row or a single column.

3798.72

-0.41 5 24 98.6 100.01 -0.3

column vectorrow vector

Page 43: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

43

VectorsTo create a row vector v with specific

numbers n1, n2, and n3:>> v = [n1 n2 n3]

Try It

Make the row vector 1 4 9 16>> v=[1 4 9 16]v = 1 4 9 16

Page 44: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

44

VectorsEach member of a vector is called an element. Elements are indexed (numbered) from left to right, with the leftmost element at index 1.

To access an element of a vector v, follow the vector name with the index in parentheses, e.g., v(4).

Page 45: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

45

VectorsExample>> v = [ 3 21 -1.1]v = 3.0000 21.0000 -1.1000>> v(2)ans = 21>> x = v(1)^3x = 27>> v(3) = -10 * v(3)v = 3 21 11

Page 46: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

46

Easy Plots“Easy Plot” family of plotting functions• Plot functions specified by notation e.g.,

sin(x), instead of by data• Plot functions specified in m-files• One- and two-dimensional functions• Make mesh, contour, surface plots• Can rotate, zoom, pan, annotate plots

Page 47: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

47

Easy Plotsezplot – plots 1D functions>> ezplot( fun )

or>> ezplot( fun, [ xmin xmax ] )

• First form’s range is -2π < x < 2π• fun is in MATLAB notation between

single quote marks, e.g., 'x^4 – 3*x^3 + 2*x – 1'

– Can use any letter

Page 48: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

48

Easy PlotsTry It

Plot the hyperbolic sine

and a chirp function

>> ezplot( '( exp(x) - exp(-x) ) / 2', [-5 5] )>> ezplot( 'sin( (2*t+3)*t )', [0 5] )

55for 2

)sinh( ≤≤−−

=−

xeexxx

( )[ ] 50for 32sin ≤≤+ ttt

Page 49: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

49

Easy Plots>> ezplot( '( exp(x) - exp(-x) ) / 2', [-5 5] )>> ezplot( 'sin( (2*t+3)*t )', [0 5] )

Extra credit: What does this sound like?

Page 50: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

50

PlottingSaving a plot in memory• Choose Edit, Copy Figure

– Go to other program, e.g., Word, PowerPoint, and paste

• On PC, to copy figure window1. Display window2. Press Alt+PrintScreen3. Go to other program and paste

Page 51: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

51

PlottingSaving a plot• To save in MATLAB format, choose

File, Save– Can work on it later– Can use as model for other plots– Can show your significant other your

that you have an artistic side

Page 52: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

52

PlottingSaving a plot• To save in format other than

MATLAB, choose File, Save As, then select type from “Save as type” dropdown box

– Can load saved figure into other software

Page 53: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

53

Plotting

Tip

• To include figure in other programs and not change size, save in raster format (BMP, JPEG, PNG, TIFF)

• To include in other programs and change size, save in vector format (EPS, EMF)

• To distribute across operating systems, save as Adobe Acrobat format (PDF)

Page 54: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

54

PlottingCAREFUL!You can’t re-create a MATLAB figure from the other formats.

If you want to work on your figure in the future, make sure you save it in MATLAB format.

Page 55: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

55

Easy PlotsCan also plot 2D functions (functions of 2 variables) as 3D plots• ezmesh – makes a mesh plot• ezsurf – makes a surface plot• ezcontour – makes a contour plot (2D projection of 3D plot)

On all of these can use any two letters as the variables. MATLAB puts them in alphabetical order and uses the first as the first variable and the second as the second variable.• 'x + 3*y + 4' is f(x,y)• 'z^2 + 2*t -8' is f(t,z), which may not be what you want

Page 56: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

56

Easy Plotsezmesh – plots 2D functions>> ezmesh( fun )

or>> ezmesh( fun, [ xmin xmax ymin ymax ] )

• First form’s range is -2π < x < 2π, -2π < y < 2π• fun is in MATLAB notation between single quote

marks, e.g., 'x^2 + y^2'

– Can use any two letters

Page 57: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

57

Easy PlotsTry It

Plot as meshes the paraboloid

and the function

ππππ 22 ,22for y22 ≤≤−≤≤−+ yxx

ππ 44 ,51for sin(y) ≤≤−≤≤− yxex

Page 58: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

58

Easy Plots>> ezmesh( 'x^2+y^2')>> ezmesh( 'exp(x) * sin(y)', [ -1 5 -4*pi 4*pi ] )

Page 59: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

59

Easy Plotsezsurf – plots 2D functions as solid surfaces>> ezsurf( fun )

or>> ezsurf( fun, [ xmin xmax ymin ymax ] )

• First form’s range is -2π < x < 2π, -2π < y < 2π• fun is in MATLAB notation between single quote

marks, e.g., 'x^2 + y^2'

– Can use any two letters

Page 60: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

60

Easy PlotsTry It

Make surface plots of the paraboloid

and the function

ππππ 22 ,22for y22 ≤≤−≤≤−+ yxx

ππ 44 ,51for sin(y) ≤≤−≤≤− yxex

Page 61: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

61

Easy Plots>> ezsurf( 'x^2+y^2')>> ezsurf( 'exp(x) * sin(y)', [ -1 5 -4*pi 4*pi ] )

Page 62: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

62

Easy Plots

To get more information out of 3D plot, can:• Rotate• Magnify• Shrink• Move• Display values at a point• Display colorbar

Page 63: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

63

Easy PlotsTo rotate, press the rotate button on the figure window toolbar, put the cursor over the plot and drag.

To return to the original position, in the command window type view(3)>> view(3)

Page 64: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

64

Easy PlotsTo zoom in (magnify), press the button with the magnifying glass and a plus on the figure window toolbar, put the cursor over the plot and click. The plot zooms in at that point. Clicking again zooms again.

To return to the original size, double click on the plot

Page 65: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

65

Easy PlotsTo zoom out (shrink), press the button with the magnifying glass and a minus on the figure window toolbar, put the cursor over the plot and click. The plot shrinks about that point. Clicking again shrinks again.

To return to the original size, double click on the plot

Page 66: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

66

Easy PlotsTo pan (move), press the button with the hand on the figure window toolbar, put the cursor over the plot and drag. Panning is particularly useful with zoomed images.

To return to the original position, double click on the plot

Page 67: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

67

Easy PlotsTry It

Try rotating, zooming, shrinking, panning and returning the plot to its original state.

Rotated Zoomed Zoomed and panned

Page 68: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

68

Easy PlotsTo display the (x,y,z) values at a point in a 3D plot, press the button with the cross and yellow box the figure window toolbar, put the cursor over the plot and click or drag.

Page 69: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

69

Easy PlotsTo see what values the colors represent, display a color bar by clicking on the colorbar button of the figure window toolbar.

To remove the colorbar, click on the button again.

Page 70: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

70

Easy Plots

Page 71: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

71

Easy PlotsA contour plot is a 2D plot of the locations where f(x,y) = k, for various constants k. This is like taking slices parallel to the x-y plane.Examples:

Isobar map

Lines of equal pressure

Topographical map

Lines of equal height

Page 72: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

72

Easy Plotsezcontour – plots 2D contours>> ezcontour( fun )

or>> ezcontour( fun, [ xmin xmax ymin ymax ] )

• First form’s range is -2π < x < 2π, -2π < y < 2π• fun is in MATLAB notation between single quote

marks, e.g., 'x^2 + y^2'

– Can use any two letters

Page 73: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

73

Easy PlotsExample

Contour plots of the paraboloid ππππ 22 ,22for y22 ≤≤−≤≤−+ yxx

Page 74: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

74

Easy Plots>> ezsurf( 'x^2+y^2')>> ezsurf( 'exp(x) * sin(y)', [ -1 5 -4*pi 4*pi ] )

Page 75: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

75

Easy Plots

Questions?

Page 76: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

76

FunctionsA function is a MATLAB program that can accepts 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 77: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

77

FunctionsThe code for a function is in an m-file. This is just a text file that ends in “.m” . 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 78: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

78

FunctionsAs 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 and save it as linear_scale.m>> edit linear_scale.m

Choose File menu, Save

Page 79: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

79

FunctionsFunction 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 linear_scaleshould be in the file called linear_scale.m

Page 80: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

80

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• input and output names do not have to (and usually don’t) match names in calling program

Page 81: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

81

Functionsfunction y = fname( v1, v2 )

• function ends when another function line appears or 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

Try It

Make the first line of your function befunction y = linear_scale( x, m, b )

Page 82: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

82

FunctionsTry It

In your file, write

function y = linear_scale( x, m, b )y = m * x + b;

Put a semicolon after each statement in your function body or the statement will print every time the function is called!

Page 83: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

83

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 84: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

84

FunctionsCall the function like this:>> linear_scale( 3.3, 2, 4.4 )ans = 11

You can save the answer by storing it in a variable:>> y = linear_scale( 100, 0.1, 5 )y = 15

Page 85: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

85

FunctionsTry It

Call your function from the MATLAB command line. • Use x = 0, m = 1, b = 10• Use x = 1, m = 0.5, b = -0.5

Page 86: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

86

Functions

Questions?• Writing functions• Calling functions

Page 87: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

87

Optimization

MATLAB itself does not have optimization functions. You can get them if you add the Optimization Toolbox.• toolbox is an extension to MATLAB that adds routines dedicated to a particular subject, e.g., optimization, image processing, etc.

Page 88: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

88

Optimization

Miami has about 10 MATLAB toolboxes which are installed when you install MATLAB. The Optimization Toolbox is one that we have.

Page 89: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

89

Optimization

The basic optimizing 1D routine is fminbnd, which attempts to find a minimum of a function of one variable within a fixed interval.• function must be continuous• only real values (not complex)• only scalar values (not vector)• might only find local minimum

Page 90: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

90

Optimizationx = fminbnd( @fun, x1, x2 )

x1 < x2 is the minimization intervalx is the x-value in [x1,x2] where the minimum occursfun is the function whose minimum we’re looking for. fun must accept exactly one scalar argument and must return exactly one scalar value

Because there are no restrictions on the value of fun, finding the minimum is called unconstrained optimization.

Page 91: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

91

Optimization

x = fminbnd( @fun, x1, x2 )@fun is called a function handle. You must include the “@” when you call fminbnd.

Page 92: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

92

OptimizationTry It

Find the minimum of f(x) = ( x – 3 )2 – 1on the interval [0,5]

Step 1 – make an m-file with the function

Page 93: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

93

OptimizationTry It

Step 2 – call fminbnd with your function>> x = fminbnd( @parabola, 0, 5 )x = 3

If you want to get the value of the function at its minimum, call the function with the minimum x value returned by fminbnd>> parabola(x)ans = -1

Page 94: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

94

OptimizationTry It

Step 3 – verify result is a global minimum by plotting function over a range, say [-10 10]>> ezplot( @parabola, [-10 10] )

Page 95: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

95

Optimization

The multidimensional equivalent of fminbnd is fminunc. It attempts to find a local minimum of a function of one or more variables.• function must be continuous• only real values (not complex)• only scalar values (not vector)• might only find local minimum

Page 96: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

96

Optimizationx = fminunc( @fun, x0 )

x0 is your guess of where the minimum isfun is the function whose minimum we’re looking for. fun must accept exactly one scalar or vector argument and must return exactly one scalar value

Page 97: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

97

Optimizationx = fminunc( @fun, x0 )

fun only has one argument. If the argument is a vector, each element represents the corresponding independent variable in the functionExample

f(x,y,z) = x2 + y2 + z2

function w = f( x ) w = x(1)^2 + x(2)^2 + x(3)^2

Page 98: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

98

OptimizationOptimizing routines such as fminunc are often sensitive to the initial value. For bad initial values they may converge to the wrong answer, or not converge at all.

Tip – if fun is a function of one or two variables, plot it first to get an idea of where the minimum is

Page 99: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

99

OptimizationTry It

Find the minimum of f(x) = ( x – π )2 – 1

Step 1 – make an m-file with the function

Page 100: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

100

OptimizationTry It

Step 2 – plot the function to get an estimate of the location of its minimum

Looks like min isat about 3

Page 101: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

101

OptimizationTry It

Step 3 – call fminunc with your function and an initial guess of 3>> xmin = fminunc( @pi_parabola, 3 )Warning: Gradient must be provided for trust-region method;

using line-search method instead.> In fminunc at 247Optimization terminated: relative infinity-norm of gradient less than options.TolFun.xmin = 3.1416

Ignore this stuff

Page 102: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

102

OptimizationTry It

Find the minimum of f(x,y) = ( x–22.22 )2 + ( y-44.44 )2 - 17

Step 1 – make an m-file with the function

Page 103: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

103

OptimizationTry It

Step 2 – plot the function to get an estimate of the location of its minimumezsurf expects a function that takes two arguments. Since parabola only takes one, we need to make a different version that takes two. Let's call it paraboloid_xy

Page 104: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

104

OptimizationTry It

Step 2 – plot the function to get an estimate of the location of its minimum>> ezsurf( @parabola_xy, [ 0 50 0 50] )

After zooming andpanning some, itlooks like the minis at about x=20and y=50

Page 105: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

105

OptimizationTry It

Step 3 – call fminunc with your function and an initial guess of [20 50]

>> x = fminunc( @paraboloid, [20 50] )x = 22.2200 44.4400>> paraboloid( x )ans = -17.0000

Page 106: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

106

OptimizationTry It

Find the minimum of a 5D hypersphere of centered at [ 1 2 3 4 5 ] f(x,y,z,a,b) = (x–1)2 + (y–2)2 + (z–3)2 +

(a–4)2 + (b–5)2

Step 1 – make an m-file with the functionUse 3 dots to continue a line in a file.

Page 107: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

107

OptimizationTry It

Step 2 – can't plot 5D, so guess [ 0 0 0 0 0]

Step 3 – call fminunc with your function and an initial guess of [0 0 0 0 0]

>> xmin = fminunc( @hypersphere, [0 0 0 0 0] )xmin = 1.0000 2.0000 3.0000 4.0000 5.0000>> hypersphere( xmin )ans = 3.9790e-012

≈ 0

Page 108: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

108

MATLAB forMTH 432

Questions?

Page 109: Introduction to MATLAB - Miami University · 2012-05-15 · Introduction to MATLAB for MTH 432. 3 Workshop information You may also want a copy of Introduction to MATLAB for MTH 453

109