Miami University

advertisement
Introduction to MATLAB
for PSY 373
(Mathematical Modeling of
Psychological Processes)
Greg Reese, Ph.D
Research Computing Support Group
Academic Technology Services
Miami University
January 2010
Workshop Information
To 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 PSY 373”
2
Workshop information
Format
• Interactive presentation with handson use of MATLAB
Requirements
• None
Duration
• Two hours
3
Outline
• Overview of MATLAB
– What is it?
– Strengths, weaknesses
• Getting started
– Numbers, variables, scalars
– Scalar arithmetic
– Variables, mathematical functions
– Getting help on MATLAB
– Quitting the program
4
Outline
Vectors
– Creating
– Combining
– Indexing
5
Outline
Data analysis
– Basic statistics
– Curve fitting
– Data simulation
– Plotting
6
Outline
Functions (MATLAB programs)
• MATLAB functions
– Using
– Finding information on
• Writing functions
– Creating
– Running
– Plotting
– Anonymous functions
– Loops
7
Overview
8
Overview
MATLAB
• Stands for MATrix LABoratory
– Originally designed for efficient
computation with matrices
• Language and environment for
technical computing
9
Overview
Capabilities
• Numerical computation
• Plotting (graphs)
• Programming
• Data acquisition
• Modeling, simulation, prototyping
• Graphical User Interface
development
• Application program development
10
Overview
Strengths*
• Algorithm development
• Easy plotting
• Quick computations
• Data analysis and visualization
In sum – GREAT for exploratory work
11
*My
opinion, of course
Overview
Weaknesses*
• Not good for final products
– Licensing costs
– Slow for certain computations
– Memory hog
– Limited GUI capabilities
In sum – not for finished products
12
*My
opinion, of course
Overview
MATLAB extendable through toolboxes
(collections of related MATLAB code)
• Commercial (cost money)
– Image processing
– Optimization
• Non-commercial (free)
– Electrophysiology (EEGLAB)
– Vision research (PsychToolbox)
13
Overview
Math functions
Graphics
Development
environment
Programming
language
External
interface
14
Overview
In this class will work on
• Development environment
• Math functions
• Writing functions
15
Overview
Development environment
• MATLAB tools and facilities
We’ll do lots
of these
things
– For running MATLAB
– For editing MATLAB programs
– For getting help on MATLAB
16
Overview
Mathematical capabilities
• LARGE number of math
computations
– Simple
• Arithmetic, trigonometry, complex numbers
– Fancy
• Matrix inverses and eigenvalues
• Bessel functions
• Fourier transforms
Don’t panic!
17
Overview
Graphics
• Easily plot data
• Annotate graphs
• 2D and 3D data visualization
• Image processing
18
Getting Started
19
Getting Started
In this class will use Windows version of
MATLAB
1. Double click on MATLAB icon
2. At prompt (>>), type pwd followed by
ENTER. Should get something like
ans =
C:\Documents and Settings\reesegj\My Documents\MATLAB
20
Getting Started
Close all windows except one with the
prompt. It’s called the command window.
Note
• After typing a MATLAB command you
always press ENTER to activate it. Won’t
show that anymore
21
Getting Started
Most of your work takes place in the
command window. After you press
ENTER you get the answer and
usually get another prompt.
Some commands though open plot
windows, run other programs, etc.
22
Getting Started
Try It
•
•
•
To learn what version of MATLAB
you have run the ver command
To find today’s date enter date
To find what directory (folder)
you’re in, use pwd (print working
directory)
23
Numbers, Scalars,
and Variables
24
Terminology
MATLAB designed to work on matrices
• matrix – a rectangular array of 1.3
numbers
-7
9
•
vector – a matrix with only one row
or column
row vector
column vector
1 7 -4.3
•
scalar – a matrix with only one row
and column, i.e., a number 1009.76
2
-3.4
8
0.05
-33.7
100
99
-23.8
25
Numbers
Numbers
• 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.02e23
7.02 10-34 is 7.02e-34
26
Numbers
Numbers
• Internally variables have precision of
about 16 decimal digits and range
from about 10-308 to 10+308
(good enough for government work!)
27
Variables
variable – a name that represents a
MATLAB object such as a scalar,
vector or matrix.
You can change (vary) the value of a
variable
28
Variables
Variable 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
29
Variables
MATLAB 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!
30
Variables
To 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'.
31
Variables
Tip – variable name should have
meaning
Example – “Number of students”
might be num_students or
numStudents, but not x or n
32
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
33
Variables
Try It
•
Make variables to represent the
following constants and set them to
the indicated values
Speed of light
Plank’s constant
Avogadro’s number
Degrees in a circle
Bottles of beer
3.00 108
6.63 10-34
6.02 1023
360
99
34
Arithmetic
MATLAB
• 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
35
Arithmetic
Symbol
Operation
+
Addition
-
Subtraction
*
Multiplication
/
Division
^
Power
Arithmetic on scalars
36
Arithmetic
You can use MATLAB as a fancy
calculator. For example, to evaluate
4x3 – 3x + 7 at x = 3.5 type
4*3.5^3 – 3*3.5 + 7
Try It
•
•
Try the above. You should get 168
Try it for x = 0 . Is MATLAB
correct?
37
Arithmetic
MATLAB has
pi to get it
as a built-in constant. Type
Try It
Compute the
• Area of a circle of radius 3:
• Area of circle, diameter 6:
• Volume of cone
(1/3)
32
(6/2)2
h r2
compute at r = 2.78 and h = 9.34
38
A = 28.27 V = 75.59
Variables
It’s more common to do arithmetic on
variables. Do it the same way as with
constants. For example:
>> radius = 5
radius = 5
>> area = pi * radius ^ 2
area = 78.5398
39
Variables
The 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 = 7
x = 7
>> x = x + 6
x = 13
>> x = 2 * x
x = 26
40
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
41
Variables
Try It
•
•
Type r=5 and ENTER
Type pi*r^2 for area
To compute area for new radius
1. Press up arrow twice
2. Use backspace key to delete the 5
3. Type 10 and ENTER
4. Press up arrow key twice
5. Press ENTER for area of new radius
42
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;
43
Variables
Try It
Use up arrow key to compute circle
area for radius of 20 and then radius of
100 but without displaying those two
values
44
Managing Variables
After a while it gets hard to remember
what variables you have and what their
values are. Here are some ways to
manage your variables.
• To display the value of a variable x:
>> x
•
If that variable doesn’t exist,
MATLAB says
??? Undefined function or
variable 'rr'.
45
Managing Variables
•
To display information about a
variable x:
>> who x
•
To display more information:
>> whos x
•
To display information about all the
current variables:
>> who
•
To display more information:
>> whos
46
Managing Variables
To display information about multiple
variables separate them by spaces
and use who or whos:
Example
Display information about x, y, z
>> who x y z
>> whos x y z
47
Managing Variables
Try It
•
•
•
•
Display the value of r
Display the value of radius
Display some information about r
and radius
Display all the information about r
and radius
48
Managing Variables
To get rid of a variable:
>> clear variable_name
To get rid of all variables:
>> clear
CAREFUL! You could lose valuable
computations that you stored in a
variable!
49
Managing Variables
Try It
•
List all your variables
•
•
Remove two of them
List all your variables again to
make sure the two are gone
50
Managing Variables
Questions?
– Numbers
– Variables
– Scalars
51
Vectors
52
Vectors
A vector is a one-dimensional matrix.
It is a single row or a single column.
37
98.72
column vector
row vector
-0.4
1 5 24 98.6 100.01 -0.3
MATLAB is designed to work with
vectors and matrices and manipulates
them very efficiently.
53
Vectors
To create a row vector v with specific
numbers n1, n2, and n3:
>> v = [n1 n2 n3]
Example
Make the row vector
>> v=[1 4 9 16]
v =
1
4
1 4 9 16
9
16
54
Vectors
Can create a column vector two ways
Method 1 – make a row vector but put
a semicolon after all but the last
number
Example
>> v=[1; 4; 9; 16]
v = 1
4
9
16
55
Vectors
transpose – the transpose of a row
vector is that vector written as a
column. The transpose of a column
vector is that vector written as a row.
In math, the transpose is often
denoted by a superscript “T”
56
Vectors
Example
1 3 5
T
1
3
5
280
13.2
1000
T
280 13.2 1000 455
455
57
Vectors
Method 2 – to make a column vector
make a row vector and transpose it by
following it with a single quote mark (')
Example
>> x=[1 4 9 16]'
x = 1
4
9
16
58
Vectors
Try It
• Make a row vector x and set it to
-3 4.2 89
• Store its transpose in t
• Display the transpose of t
59
Vectors
>> x = [ -3 4.2 89 ]
x = -3.0000
4.2000
89.0000
>> t = x'
t = -3.0000
4.2000
89.0000
>> t'
ans = -3.0000
4.2000
89.0000
60
Vectors
Each member of a vector is called an
element. The number of elements in a
vector is its size or length.
To get the length of a vector v use
>> length(v)
MATLAB provides some easy ways to
generate common vectors.
61
Vectors
Command
Operation
zeros(1,n)
Create a row vector of n zeros
ones(1,n)
Create a row vector of n ones
rand(1,n)
Create a row vector of n
numbers uniformly distributed
between 0 and 1
Create a row vector of n
normally distributed numbers
with mean 0 and std. dev. 1
randn(1,n)
62
Vectors
To generate column vectors
1. Interchange 1 and n in the function call,
or
2. Store the transpose of the row vector
Example
ones(3,1)
ans =1
1
1
ones(1,3)'
ans = 1
1
1
63
Vectors
You can easily create a row vector of
consecutive numbers by using a colon
m:k:n
• Makes
m m+k m+2k … n-k n
• If k is not specified, uses k = 1
• If n < m get descending sequence
• m, k, or n can be integer or floating
point
64
Vectors
Example
3:7
3 4 5 6 7
10:2:20
10 12 14 16 18 20
7:-1:4
7 6 5 4
1:0.1:1.5
1 1.1 1.2 1.3 1.4 1.5
65
Vectors
The colon is particularly useful for
making a sequence of values of an
independent variable that can be used
to evaluate the dependent variable.
66
Vectors
Try It
Evaluate et from 0 to 2.5 in steps of 0.5
>> t=0:0.5:2.5
t =0 0.5
1.0 1.5 2.0 2.5
>> y=exp(t)
y = 1.00 1.65 2.72 4.48 7.39 12.18
67
Vectors
One of MATLAB’s big strengths is its
ability to let you easily make plots. To
plot a vector y use the command
plot(y).
plot(y) plots values of y versus the
element number. In this case, since t
has 7 elements, the element numbers
are 1,2, … 6,7.
68
Vectors
Try It
Plot the y produced previously
69
Plotting
To plot values in the vector x on the
horizontal axis and in the vector y on
the vertical axis:
• >> plot(x,y)
•
x and y must be same dimension
Try It
Make a plot of t on the horizontal axis
and y on the vertical axis
70
Plotting
Note that horizontal axis of plot now has
values in t, not element numbers.
71
Plotting
Try more
• Plot the sine from -5 to 5 at
intervals of 0.01 ( sin(t) )
•
Plot the following from -20 to 20 at
intervals of 0.5
– arctangent ( atan(t) )
– sign ( sign(atan(t)) )
– absolute value of the arctangent
( abs(atan(t)) )
72
Vectors
To erase a vector (remove all its
elements) set it to empty square brackets,
e.g., v = []
Example
>> v=[3 5]
v = 3 5
>> v=[]
v =[]
>> length(v)
ans = 0
73
Vector in functions
Most MATLAB functions work on
vectors. They evaluate the function at
every element of the vector. The
result is a vector of the same
dimension, i.e., both input and output
vectors have the same number of
elements and they are both either row
vectors or column vectors
74
Vectors and Scalars
When performing arithmetic between
a scalar and vector MATLAB does the
arithmetic between the scalar and
each element of the vector. This is
called elementwise arithmetic.
75
Vectors and Scalars
Example
• Let x = 1 3 5 7
– x + 4 = 1+4
= 5
– x / 2 = 1/2
= 0.5
3+4
7
3/2
1.5
5+4
9
5/2
2.5
7+4
11
7/2
3.5
Dividing a scalar by a vector produces
an error
76
Vectors and Scalars
Try It
Let x = 2 4 6
Compute
• x+4
• 4+x
• x-4
• 4*x
• x/4
• 4/x
77
Combining vectors
x and y are vectors of same dimension
• x + y is elementwise sum
• x – y is elementwise difference
• x .* y is elementwise multiplication
• x ./ y is elementwise division
• x .^ y is elementwise power
Make sure you put the period in front of the
arithmetic operation on the last three
78
Combining vectors
Try It
Make the vectors x = 1 2 3
y = 4 5 6 and z = 7 8
Compute
• x + y, y – x, and x + z
• x .* y, x ./ y, and x .^ y
79
Concatenation
concatenation - putting vectors
together sequentially. Also called
appending
To concatenate row vectors put in
square brackets separated by spaces,
e.g., [v1 v2 v3]
80
Concatenation
Example
>> x=[14 21];
>> y=[-2 13 -39];
>> z=[x y]
z = 14
21
-2
>> [y x]
ans =
-2
13
-39
13
14
-39
21
81
Concatenation
Example
Make a plot of a vector whose first ten
elements are the numbers 1 through
10 and whose last ten elements are
the numbers 10 through 1
>> f=[1:10 10:-1:1];
>> plot(f)
82
Concatenation
Try It
Make and plot a vector whose first ten
elements are 1 through 10, whose
second ten elements are all 10, and
whose last ten elements are 11.5 .
(Hint: use ones(1,10) and multiply by
a scalar)
83
Concatenation
>> f=[1:10 10*ones(1,10) 11.5*ones(1,10)];
>> plot(f)
84
Vectors as sets
You can treat vectors as mathematical
sets and combine them by set
operations, such as the union,
intersection, exclusive-or, etc. If you’re
interested, type help ops on the
MATLAB command line.
85
Vector Indexing
86
Vector indexing
Sometimes you need access to
individual elements of a vector. You
can do this by referring to an
element’s index or subscript. This is
the position of the element in the
vector.
87
Vector indexing
The indexes of a vector run from 1 to
N, where N is the length of the vector.
• Using an index less than one or
greater than the length of a vector
makes MATLAB display an error
88
Vector indexing
Important indexes
• The first (leftmost) element of a
row vector has index 1
• The first (topmost) element of a
column vector has index 1
89
Vector indexing
The last index of a vector is equal to
the length of a vector
• The rightmost element of a row
vector is the last element
• The bottom element of a column
vector is the last element
90
Vector indexing
To access a particular element of a
vector write the vector’s name
followed by the index in parentheses
To access the last element of a vector
use the word “end” as an index
instead of a number
91
Vector indexing
Example
>> x=[39 24 8 20 5];
>> x(1)
ans = 39
>> x(4)
ans = 20
>> x(end)
ans = 5
>> x(6)
??? Index exceeds matrix dimensions.
92
Vector indexing
Example
>> x(0)
??? Subscript indices must either be
real positive integers or logicals.
>> x
x =
39
24
8
20
5
>> x(1)=x(end)
x =
5
24
8
20
5
>> x(2)= (x(2)-4)^2 + 44;
>> x
x =
5
444
8
20
5
93
Vector indexing
To remove an element from a vector
set the indexed element equal to
empty square brackets - [ ]
x = 6
5
4
>> x(1)=[]
x =
5
4
>> x(end)=[]
x =
5
4
>> x(2)=[]
x =
5
3
3
2
3
1
2
3
2
1
2
94
Vector indexing
You can delete multiple elements of a vector
by setting the indexed vector to empty square
brackets
Example
>> x=1:10
x = 1 2 3 4 5
>> x(2:2:10)=[]
x = 1 3 5 7 9
>> x([1 end])=[]
x = 3 5 7
6
7
8
9
10
95
Vector indexing
Try It
The weights of some gerbils at the
start of an experiment are
2, 13, 9, 10, 9, 8, 1
Make a vector of the gerbil weights
>> weights=[2 13 9 10 9 8 1];
96
Vector indexing
Try It
Change the vector to reflect the situation
at the end of the experiment
• The second gerbil’s weight doubled
>> weights(2)=2*weights(2);
•
The 4th gerbil lost half its weight
>> weights(4)= weights(4)/2;
97
Vector indexing
Try It
• The second-to-last gerbil weighed
as much as the third gerbil
>> weights(end-1)=weights(3);
•
The last gerbil died and was
removed from the experiment
>> weights(end)=[]
weights =
2.0000 26.0000
9.0000 5.0000 9.0000 9.0000
98
Vector indexing
You can use a vector as an index, not
just a scalar. The result is a vector of the
same length as the index vector.
For example, v( [i1 i2 i3] ) returns a
vector of length 3 whose first element is
v(i1), whose second element is v(i2) and
whose last element is v(i3)
99
Vector indexing
Example
>> x=[39 24 8 20 5];
The first and last elements
>> x([1 end])
ans = 39
5
All but the first and last elements
>> x(2:end-1)
ans = 24
8
20
100
Vector indexing
Example
>> x=[39 24 8 20 5];
The odd-numbered elements
>> x(1:2:end)
ans = 39
8
5
The even-numbered elements
>> x(2:2:end)
ans = 24
20
101
Sorting
You can sort the numbers in a vector and
then use vector indexing to get useful
information.
>> x=[99 -3 3.14 2.78];
>> sort(x)
ans = -3.0000 2.7800 3.1400 99.0000
sort(x)returns a vector of the same
dimension as x but with the numbers
sorted from lowest to highest
102
Sorting
Try It
Make a vector of these numbers:
27.4, 39.2, 49, 950, 95.6, 30.8, 40.2
>> v = [ 27.4 39.2 49 950 95.6 30.8 40.2 ];
Sort the vector and store the sorted numbers
>> vSorted = sort( v )
vSorted = 27.4000
30.8000
40.2000
49.0000
95.6000
39.2000
950.0000
103
Sorting
Try It
What are the two lowest numbers?
>> vSorted(1:2)
ans = 27.4000
30.8000
What are the two highest numbers?
>> vSorted(end-1:end)
ans = 95.6000 950.0000
104
Sorting
Try It
What is the mean value of all the
numbers? Hint: use mean()
>> mean(vSorted)
ans = 176.0286
What is the mean value, excluding the
highest and lowest numbers?
>> mean( vSorted(2:end-1) )
ans = 50.9600
105
Logical Indexing
106
Logical indexing
Another method of selecting elements is to
choose those that meet some criterion, e.g.,
the elements that are greater than zero, the
elements that are not more than three
standard deviations from the mean, etc.
MATLAB does this by
logical indexing.
107
Logical indexing
MATLAB has the usual relational operators.
Symbol
==
~=
<
>
<=
>=
Operation
Equal
Not equal
Less than
Greater than
Less than or equal
Greater than or equal
To get more information, type help ops
108
Logical indexing
The result of comparing two scalars is a logical
value. A logical value can only be true or false.
MATLAB represents true by the number 1 and
false by 0.
• Can also use the keywords true and false
109
Logical indexing
Example
>> x=5;
>> x>5
ans = 0
>> x<=5
ans = 1
>> x==5
ans = 1
>> x~=5
ans = 0
110
Logical indexing
If you write a command that compares a
vector to a scalar, MATLAB does an
elementwise comparison. The result is a
vector of logical values. It has the same
dimension as the vector in the comparison.
111
Logical indexing
Example
>> x=8:12
x =
>> x>10
ans =
>> x==11
ans =
>> x>=7
ans =
8
9
10
11
12
0
0
0
1
1
0
0
0
1
0
1
1
1
1
1
112
Logical indexing
MATLAB provides logical operations such as
AND, OR, NOT, etc.
• Can compare two scalars
• If compare scalar to vector, do
elementwise comparison
• If compare two vectors, must both be
same dimension
To get more information, type help ops
113
Logical indexing
Symbol
&
|
xor()
~
any()
all()
Operation
AND – true if both elements are nonzero, false
otherwise
OR – true if one or both elements are nonzero,
false otherwise
EXCLUSIVE OR – true if exactly one element is
nonzero, false otherwise
NOT – makes nonzero element zero and zero
element one
True if any element of a vector is nonzero, false
otherwise
True if all elements of a vector are nonzero, false
otherwise
114
Logical indexing
Example
>> age=[45 47 15 13 11]
age =
45
47
15
13
11
1
0
Who is a teenager?
>> age>=13 & age<=19
ans =
0
0
1
115
Logical indexing
Example
>> age=[45 47 15 13 11]
age =
45
47
15
13
11
0
1
0
1
Who is not a teenager?
>> ~(age>=13 & age<=19)
ans =
1
1
0
Who is an adult or a child?
>> age>19 | age<13
ans =
1
1
0
116
Logical indexing
Example
>> age=[45 47 15 13 11]
age =
45
47
15
13
11
Are there any teenagers?
>> any( age >= 13 & age <= 19 )
ans = 1
Are all the people teenagers?
>> all( age >= 13 & age <= 19 )
ans = 0
117
Logical indexing
For even more power you can use logical
values as subscripts. This is called logical
indexing or logical subscripting.
To perform logical subscripting on a
vector x, pass it (in parentheses) a logical
vector of the same dimension. The result
is a vector of all the elements of x for
which the logical vector is true.
118
Logical indexing
Example
>> age=[45 47 15 13 11]
age =
45
47
15
13
11
1
0
Who is a teenager?
>> age>=13 & age<=19
ans =
0
0
1
How old are the teenagers?
>> age( age >= 13 & age <= 19)
ans =
15
13
119
Logical indexing
Tip
If you’re going to use the results of a
calculation a lot, compute it once and
save it in a variable.
120
Logical indexing
Example
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
>> teenager = age>=13 & age<=19;
>> age(teenager)
Ans =
15
13
>> weight(teenager)
ans =
113
125
121
Logical indexing
Tip
Since relational and logical operations
return 1 if they meet a criterion and 0 if
they don’t, you can count the number
of elements in a vector that meet a
criterion by finding the sum of the
logical vector result.
• The function sum returns the sum
of a vector’s elements
122
Logical indexing
Example
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
How many teenagers are there?
>> sum( age >= 13 & age <= 19 )
ans = 2
How many people weigh more than 200 lbs?
>> sum( weight > 200 )
ans = 1
123
Logical indexing
Try It
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
How many adults are there?
>> sum( age >= 20 )
ans = 2
How many children are there?
>> sum( age < 13 )
ans = 1
124
Logical indexing
Try It
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
How many adults weigh more than
200 lbs?
>> sum( age >= 20 & weight > 200 )
ans = 1
How many children weigh less than 100 lbs?
>> sum( age < 13 & weight < 100 )
ans = 1
125
Logical indexing
The find function is related to logical
indexing. It returns the indexes of the
elements of a vector that are nonzero.
You can use those indexes to select the
elements of a vector that meet a criterion.
find is most helpful when used on logical
vectors.
126
Logical indexing
Example
>> age=[45 47 15 13 11];
>> find( age >= 13 & age <= 19 )
ans =
3
4
How old are the teenagers?
>> age( find( age>=13 & age <=19 ))
ans =
15
13
127
Logical indexing
Example – use find
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
How old is the second teenager?
>> indexes = find( age >= 13 & age <= 19 )
indexes = 3
4
>> age( indexes(2) )
ans = 13
128
Logical indexing
Try It – use find
>> age=[45 47 15 13 11];
>> weight=[202 151 113 125 94];
How much does the second teenager
weigh?
>> indexes = find( age >= 13 & age <= 19 )
indexes = 3
4
>> weight( indexes(2) )
ans = 125
129
Logical indexing
In the fall of 2004 entering freshmen at Miami
University were surveyed. One of the questions was
to write the number of hours of alcohol education or
prevention the students have had. The responses
are numbers from 0 to 4 with 0 to 3 being the actual
number of hours and 4 representing more than 3
hours. Some students did not respond at all.
Load the answers to the question with the
command
>> allAnswers = load( 'survey.txt' )
130
Logical indexing
MATLAB has a built-in constant called NaN,
which stands for not-a-number. It represents
the result of mathematically undefined
operations, such as 0 / 0 or ∞ - ∞ (infinity
minus infinity). It also marks missing data
points.
isnan(x) returns true if x is NaN and false
otherwise.
131
Logical indexing
Try It
In the survey, students who didn’t
answer the question are represented by
NaN. Answer the following questions:
• How many students were in the
survey?
>> length( allAnswers )
ans = 531
•
How many students did not answer
the survey question?
>> sum( isnan( allAnswers ) )
ans = 59
132
Logical Indexing
Try It
Make a vector (called answers) for only
the students who answered.
(Hint: store allAnswers in answers,
then delete all members of answers
that are NaN)
>> answers = allAnswers;
>> answers( isnan(answers) )=[];
Determine how many students answered
>> length( answers )
ans = 472
133
Logical Indexing
Try It
Consider only students who responded
to the survey when answering the
following questions about the amount
of college alcohol-prevention education
the students had.
• Are all the values in your new vector
legal, i.e., between 0 and 4 inclusive?
>> all( answers>=0 & answers<=4 )
ans = 1
134
Logical Indexing
Try It
What percentage didn’t have any
prevention education?
100 * sum( answers==0 ) / length( answers )
ans = 39.6186
For every student who had the maximum
amount of prevention education, how many
had none?
>> sum( answers==0 ) / sum( answers==4 )
ans = 1.8515
135
Logical Indexing
Try It
What was the average number of hours of
prevention education for students who had 1,
2, or 3 such hours?
>> mean( answers(answers>0&answers<4) )
ans = 2.0435
136
Data Analysis
137
Data analysis
MATLAB has functions for the basic
statistical analysis of numbers stored in
a vector. The table that follows shows
some of them. For more details, type
help datafun
at the command line.
138
Data analysis
max
min
mean
median
std
var
sum
prod
hist
Largest component.
Smallest component.
Average or mean value.
Median value.
Standard deviation.
Variance.
Sum of elements.
Product of elements.
Histogram.
139
Data analysis
Example
Make a vector of a class’s quiz
grades: 2, 9, 8, 5, 4, 5, 8, 10, 7, 7
>> grades = [2
9
8
5
4
5
8
10
7
7];
Compute the average quiz score:
>> mean(grades)
ans = 6.5000
140
Data analysis
Try It
Make a vector of a class’s quiz
grades: 2, 9, 8, 5, 4, 5, 8, 10, 7, 7
>> grades = [2
9
8
5
4
5
8
10
7
7];
Show the number of grades
>> length( grades )
ans = 10
141
Data analysis
Try It
Find the minimum, maximum,
median, and mode of the grades
>> min( grades )
ans = 2
>> max( grades )
ans = 10
>> median( grades )
ans = 7
>> mode( grades )
ans = 5
142
Data analysis
MATLAB has other analysis functions
• Histograms
• Cumulative products
• Finite differences
• Fourier transforms
For more information, type
help datafun
143
Data analysis
MATLAB is great for data simulation.
Example
• Simulate readings of data taken
every tenth of a second for 10
seconds. The nominal reading of
10 has been corrupted by additive,
normally-distributed noise of mean
0 and variance 4
n(t)
x(t)
+
y(t) = x(t) + n(t)
144
Data analysis
2*randn(1,n) makes a vector of n
normally distributed numbers with
mean 0 and variance 4
>> t=0:0.1:10;
>> y=10+2*randn(1,length(t));
>> plot(t,y)
n(t)
x(t)
+
y(t) = x(t) + n(t)
145
Data analysis
Ideally, the mean of y(t) should be
10 and the variance should be 4. Use
the MATLAB functions mean and var
to compute these values.
>> mean(y)
n(t)
ans = 10.3049
x(t)
+
y(t) = x(t) + n(t)
>> var(y)
ans = 4.2433
(We’ll discuss mean and var more later)
146
Plotting
147
Plotting
Let’s do some more data simulation and
along the way, learn how to change the
details of a plot.
Situation – an electrical component has a
steady power output. Then, for 10
seconds, its output increases linearly. The
measurements are noisy.
148
Plotting
First, assume the output is 10 watts and then
increases linearly at 0.5 watts per second.
Let’s sample this every 1/10 second.
>>
>>
>>
>>
>>
p0=10;
slope=0.5;
time=0:0.1:10;
data=slope*time+p0;
plot(time,data)
149
Plotting
Your figure window should look like this
15
14.5
14
13.5
13
12.5
12
11.5
11
10.5
10
0
1
2
3
4
5
6
7
8
9
10
150
Plotting
Next, let’s make noise that is normally
distributed with mean=0 and variance=4
>> noise=2*randn(1,length(data));
>> plot(time,noise)
151
Plotting
Your figure window should look like this
15
14.5
14
13.5
13
12.5
12
11.5
11
10.5
10
0
1
2
3
4
5
6
7
8
9
10
152
Plotting
Next, let’s add the noise to the data to
simulate noisy data
>> data = data + noise
>> plot(time,data)
153
Plotting
Your figure window should look like this
15
14.5
14
13.5
13
12.5
12
11.5
11
10.5
10
0
1
2
3
4
5
6
7
8
9
10
154
Plotting
The data seems to be very noisy but this
is an effect due to the vertical scale,
which goes from 5 to 20. Let’s start the
scale at 0.
There are two general ways to change the
plot – by MATLAB commands or
interactively through a graphical user
interface (GUI). We’ll use the GUI.
155
Plotting
Click here
In the figure window, click on the
rightmost button of the tool bar.
156
Plotting
Click here
Click on the arrow button in the tool bar. This
lets you select what part of the plot to work on
157
Plotting
To change the vertical axis, left click on
either axis. The big box on the bottom will
now say “Property Editor – Axes”
1. Click on the y-axis tab
2. Put in 0 and 20 for the y limits
3. Click on the figure and watch the plot
change
158
Plotting
Get fancier
1. On the y-axis tab, enter the label
“Power (watts)”
2. On the x-axis tab, enter the label
“Time (sec)”
3. In the title box, add the title
“Power measurements in first 10 secs”
4. Click on the title and in the Property
Editor change the font to 16 pt bold
159
Polynomial fit
You might look at the data and see that a
straight line could fit it well. There are two
ways to find the best-fit line or best fit
polynomial.
Manual method
• The function polyfit( x, y, n )
fits an nth degree polynomial to the
values in y by evaluating the
polynomial at the values in x
160
Polynomial fit
Manual method
• The function polyfit( x, y, n )
fits an nth degree polynomial to the
values in y by evaluating the
polynomial at the values in x
• polyfit returns a vector of n+1
coefficients with that of the highest
power coming first
• For the best fit line, use n = 1
161
Polynomial fit
In the command window, do this
>> c=polyfit(time,data,1)
>> c =
0.6011
9.2672
>> best_fit=c(1)*time+c(2);
•
•
The third line creates a vector with
points from the best-fit line
Note that the coefficients are
reasonably close to their ideal values
of 0.5 and 10
162
Polynomial fit
If you plot the line by typing
plot(time,best_fit) you would
overwrite the current plot. To add to the
current plot type hold on first.
>> hold on
>> plot(time,best_fit)
To replace the plot, type hold off
before plotting.
163
Polynomial fit
To replace the plot, type hold off
before plotting.
164
Polynomial fit
Automatic method
Try It
• Click on best-fit line, press delete key
• Select Tools, Basic fitting
• Select “linear”
• Select “Show equations”
Immediately get best-fit line and
equation!
Delete line and repeat for best fit cubic
polynomial
165
Plotting
Try It
Go to the figure window and
• Change the color of the line to red
• Draw an “x” at each data point
• Change the names of the data
series to “Data” and “Best fit line”
• Add a legend (see Insert menu)
• Add horizontal grid lines
166
Plotting
Try More
• Manually draw a red circle around
the highest point.
• Insert a text arrow near the circle
with the word “Maximum” and the
arrow pointing to the circle
• Change the background color
To see what your figure will look like if
you print it, select “Print preview” from
the File menu
167
Plotting
Saving a plot in memory
• Choose Edit, Copy Figure
– Go to other program, e.g., Word,
PowerPoint, and paste
•
On PC, to copy figure window
1. Display window
2. Press Alt+PrintScreen
3. Go to other program and paste
168
Plotting
Saving 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
169
Plotting
Saving 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
170
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)
171
Plotting
CAREFUL!
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.
172
Plotting
Questions?
173
Matrices and
Linear Algebra
174
Matrices
For our purposes, a MATLAB matrix is a
rectangular array of real numbers. An
m n matrix has m rows and n columns.
In general, MATLAB matrices can
• have more than
a11 a12  a1n
two dimensions
a21 a22  a2 n
• can have complex m rows




numbers
am1 am 2  amn
• “array” and “matrix” are
used informally as synonyms
n columns
175
Matrices
We denote the element in the ith row and
jth column of the matrix A as aij
i.e., the first (left) number in the subscript
is the row number and the second (right)
number is the column number.
A
a11
a12
 a1n
a21

a22

 a2 n


am1
am 2  amn
176
Matrices
Similarly, in MATLAB we access the
element in the ith row and jth column of
the matrix A by typing A(i,j)
i and j are called the array indices
For an m n MATLAB matrix A
– the top row is row 1
– the bottom row is row m
– the left column is column 1
– the right column is column n
A
a11
a12
 a1n
a21

a22

 a2 n


am1
am 2  amn
If you use an index outside of that range,
MATLAB will report an error
177
Matrices
To create a matrix with specific numbers
in it:
• in square brackets, write the numbers from
the top row to the bottom row
• separate the numbers with spaces
• place a semicolon between each row
Example
>> A = [ 4 3 9 0; -20 3.2 3.8 44.4; 0 0 -2 10]
A =
4.0000
3.0000
9.0000
0
-20.0000
3.2000
3.8000
44.4000
0
0
-2.0000
10.0000
178
Matrices
There are commands to create common
matrices:
Command
Operation
zeros(m,n)
Create an m n matrix of zeros
ones(m,n)
Create an m n array of ones
rand(m,n)
Create an m n array of numbers
uniformly distributed between 0 and 1
randn(m,n)
Create an m n array of zeros
normally distributed numbers with
mean 0 and std. dev. 1
eye(m,n)
Create an m n identity matrix
179
Matrices
There are commands to create
specialized matrices. A few are:
Command
Operation
magic(n)
Create an n n magic square
hilb(n)
Create a Hilbert matrix of order n
Hadamard(n)
Create a Hadamard matrix of order n
Toeplitz(r)
Create a symmetric Toeplitz matrix
with r as the first row
180
Matrices
Just as with vectors, you can perform
elementwise arithmetic on matrices.
The matrices must have the same
dimensions. The arithmetic is between
each pair of corresponding elements.
Example
9
1
0
0
0
5
20
10
0
1
12
10
1
0
5
10
5
9
2
1
0
10
15
0
10 0
12
181
Matrices
A and B are matrices of same dimension
• A + B is elementwise sum
• A – B is elementwise difference
• A .* B is elementwise multiplication
• A ./ B is elementwise division
• A .^ B is elementwise power
Make sure you put the period in front of
the arithmetic operation on the last three
182
Matrices
Matrix multiplication is a special operation
between two matrices A and X. If A is an
m p matrix, X must have p rows, though it
could have any number of columns, say n.
The result of the matrix multiplication is an
m n matrix Y.
AX
m
p
p
n
Y
m
n
183
Matrices
Example
3 2 0 1
4 10 5 1
0
2
0 4
1
1
0
3
4
2
7
2
y11
y21
y12
y22
y31
y32
184
Matrices
3 2 0 1
4 10 5 1
0
2
0 4
1
0
3
1
4
2
y11
y21
y12
y22
y31
y32
To get y11, the element
in the first row and
column of the output:
• multiply the first number of the first row of A by the first
A
number of the first column of X
(3
7
2
X
Y
-1 )
• multiply the second number of the first row of A by the
second number of the first column of X
(2
0)
• continue until you multiply the last number of the first row
of A by the last number of the first column of X ( 1
• y11 is the sum of these products,
i.e., y11 = 3 (-1) + 2 0 + 0 3 + 1 7 y11 = 4
7)
185
Matrices
A nice way to remember this is to
1. Slide the first row down and parallel to the
first column until the two are lined up
3 2 0 1
* * * *
* * * *
1 *
0
3
*
*
7
*
y11 *
* *
*
*
3( 1)
2 ( 0)
0 (3)
1 (7)
y11
186
3 ( 1)
Matrices
2 ( 0)
0 (3)
2. Multiply corresponding
numbers
1 (7 )
3. Sum the products
3 ( 1)
3 2 0 1
4 10 5 1
0
2
0 4
1
1
0
3
4
2
7
2
4
y21
y12
y22
y31
y32
y11
2 ( 0)
y11
0 (3)
y11
4
1 (7 )
187
Matrices
Example
Now try the first row and second column
3 2 0 1
4 10 5 1
0
2
0 4
1
1
0
3
4
2
7
2
4
y21
y12
y22
y31
y32
188
Matrices
Example
First row, second column
*
1
3 2 0 1
*
* * * *
*
* * * *
*
3
4
2
10
0
5
1
1
0
2
0
4
4
2
2
1
1
0
3
4
2
7
2
4
*
y12
*
*
*
3 (1)
2 (4)
0 ( 2)
1 ( 2)
4
y21
13
y22
y31
y32
y12
y12
3 (1) 2 (4) 0 ( 2) 1 (2)
y12 13
189
Matrices
Try It
Second row, first column
3
4
2
10
0
5
1
1
0
2
0
4
3
4
2
10
0
5
1
1
0
2
0
4
1
1
0
3
4
2
7
2
1
1
0
3
4
2
7
2
4
y21
13
y22
y31
y32
4 ( 1)
10 (0)
5 (3)
1 (7 )
4
26
13
y22
y21
y31
y32
y21
y21
4 ( 1) 10 (0) 5 (3) 1 (7)
26
190
Matrices
Try It
Second row, second column
3
4
2
10
0
5
1
1
0
2
0
4
3
4
2
10
0
5
1
1
0
2
0
4
1
1
0
3
4
2
7
2
1
1
0
3
4
2
7
2
4
26
13
y22
y31
y32
4
26
13
28
y31
y32
y22
y22
4 (1) 10 (4) 5 ( 2) 1 (2)
28
191
Matrices
Try It
Third row, first column
3 2 0 1
4 10 5 1
0
3
4
2
10
0
5
1
1
0
2
0
4
2 0 4
1
1
0
3
4
2
7
2
1
1
0
3
4
2
7
2
4
26
13
28
28
y32
4
26
13
28
y31
y32
y31
0 ( 1) 2 (0) 0 (3) 4 (7)
y31
28
192
Matrices
Try It
Third row, second column
3 2 0 1
4 10 5 1
0
3
4
2
10
0
5
1
1
0
2
0
4
2 0 4
1
1
0
3
4
2
7
2
1
1
0
3
4
2
7
2
4
26
13
28
28
16
4
26
13
28
28
y32
y32
0 (1) 2 (4) 0 ( 2) 4 (2)
y32 16
193
Matrices
Final solution is:
3
4
2
10
0
5
1
1
0
2
0
4
1
1
0
3
4
2
7
2
4
26
13
28
28
16
194
Matrices
In MATLAB, to multiply matrix A by
matrix X, simply type A*X
Try It
Create matrices A and X and compute
their matrix product
3
4
2
10
0
5
1
1
0
2
0
4
A
1
1
0
3
4
2
7
2
X
4
26
13
28
28
16
Y
195
Matrices
A special, but common, case is when
the matrix X is a column vector
Try It
Compute the matrix product A X by
hand and then with MATLAB
1
4
0
1
10
1
6
3
y1
y2
4
y1
5
2
8
1
y3
28
y2
Y
44
y3
A
X
196
Matrices
Multiplication of a matrix by a vector is
important because it occurs often in
linear algebra, which in turn appears a
lot in applied math.
197
Linear Algebra
A common problem is to solve a set of
n simultaneous, linear equations in n
unknowns, i.e.,
a11 x1 a12 x2  a1n xn
y1
a21 x1 a22 x2  a2 n xn

y2

an1 x1 an 2 x2  ann xn
yn
198
Linear Algebra
By using the previous definition of matrix
multiplication, we can rewrite the set of
equations in matrix form…
a11 x1 a12 x2  a1n xn
y1
a21 x1 a22 x2  a2 n xn

y2

an1 x1 an 2 x2  ann xn
yn
a11
a12  a1n
x1
y1
a21

a22  a2 n



x2

y2

an1
an 2  ann
xn
yn
199
Linear Algebra
and even more simply as
AX
Y
where
A
a11
a12  a1n
x1
y1
a21

a22  a2 n



x2

y2

an1
an 2  ann
X
xn
n
n
n
Y
yn
1
n
1
200
Linear Algebra
To solve a set of n simultaneous, linear equations in
n unknowns, follow these four steps.
Step 1
a11 x1 a12 x2  a1n xn
y1
a21 x1 a22 x2  a2 n xn

y2

On paper, rewrite the equations
an1 x1 an 2 x2  ann xn
in the form on the right.
• put all the unknowns in the same order (x1, x2, … xn)
• if an equation is missing an unknown, write it in with a
coefficient of zero
y
x
10
5
100 10 x 5 y
0
0
0 x y 10
x 0 y 5
0
0
0
10 x 5 y 0
100
yn
201
Linear Algebra
Step 2
Rewrite the equations in matrix form.
a11 x1 a12 x2  a1n xn
y1
a11
a12  a1n
x1
y1
a21 x1 a22 x2  a2 n xn

y2

a21

a22  a2 n



x2

y2

an1 x1 an 2 x2  ann xn
yn
an1
an 2  ann
xn
yn
0 x y 10
x 0 y 5
0
0
0
1
10 x 5 y 0
100
10
5
10
5
x
y
AX
Y
A
0
1
10
1
0
5
0
AX
1
0
X
Y
Y
10 x
5 y
0
0
0
100
0
0
100
202
Linear Algebra
Step 3
Enter the matrices A and Y into MATLAB
>> A = [ 0 1 -10; 1 0 -5; -10 -5 0 ]
A =
0
1
-10
1
0
-5
-10
-5
0
AX
A
0
1
10
Y
1
0
5
10
5
0
X
x
y
Y
0
0
100
>> Y = [ 0 0 -100]'
Y =
0
0
-100
203
Linear Algebra
Step 4
Solve with the command
X = A \ Y
>> X = A \ Y
X =
5
10
1
X
x
y
5
10
1
204
Linear Algebra
You can check your solution by multiplying
the matrices A and X and verifying that
they equal Y
>> A * X
ans =
0
0
-100
>> Y
Y =
0
0
-100
205
Linear Algebra
Try It
Step 1- on paper,
rewrite the equations in
the form on the right.
3x 6 z 3 y
x 5 y 10 z 20
2z y x 2
a11 x1 a12 x2  a1n xn
y1
a21 x1 a22 x2  a2 n xn

y2

an1 x1 an 2 x2  ann xn
yn
0
0
0
3x 3 y 6 z
x 5 y 10 z
x
y 2z
0
20
2
206
Linear Algebra
Try It
Step 2 - rewrite the
equation in matrix form
3x 3 y 6 z
x 5 y 10 z
x
y 2z
a11
a12  a1n
x1
y1
a21

a22  a2 n



x2

y2

an1
an 2  ann
xn
yn
0
20
2
3
1
3
5
6 x
10 y
0
20
1
1
2
2
z
207
Linear Algebra
Step 3 - enter the
matrices A and Y into
MATLAB
A
3
1
3
5
6
10
1
1
2
X
x
y
z
Y
0
20
2
>> A = [ 3 3 -6; 1 -5 -10; 1 1 2 ]
A =
3
3
-6
1
-5
-10
1
1
2
>> Y = [ 0 20 2]'
Y =
0
20
2
208
Linear Algebra
Step 4 – solve with the command X = A \ Y
>> X = A \ Y
X =
5.0000
-4.0000
0.5000
x
X
y
z
5
4
1
2
209
Linear Algebra
You can check your solution by multiplying
the matrices A and X and verifying that
they equal Y
>> A * X
ans =
0
20
2
>> Y
Y =
0
20
2
210
Questions
Questions
on
Solving
Simultaneous
Equations?
211
Using MATLAB
Functions
212
Functions
You’re likely to want to compute
functions of a variable, e.g.,
x
e
kx
ln( x)
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.
213
Functions
Example
e
x
x
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)
214
Functions
You can make complicated expressions
by combining variables, functions, and
arithmetic, e.g.,
Math
5e
kt
17.4 sin 2 t T
“*” means “ ”
5*exp(-k*t)+17.4*sin(2*pi*t/T)
MATLAB
Note how similar math and MATLAB are.
215
Functions
Try It
• Compute these
2
•
4
0
.
2
x
e
for
x 8
The sine of 90 is 1. Use the
MATLAB function sin to
compute the sine of 90 .
Waz up?
216
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
217
Getting help
The help information explains that
the argument is in radians, not
degrees.
218
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.
219
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”.
220
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
221
Getting help
Questions?
• Help
222
Writing Functions
223
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.
224
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
a=?
Output
b=9
225
Writing Functions
The 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
226
Writing Functions
• What path does the baseball take?
• How far does it go?
• What's the best angle to throw it at?
227
Writing Functions
Height
y(t)
V
θ
t
Time
y(t) = v sinθ t – ½ gt2
• v is initial speed (velocity)
• g is 32 feet/sec2
• t is time
• θ is throw angle
228
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
229
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
230
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
231
Writing Functions
function 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 be
function h = height( time )
232
Writing Functions
Pitcher #1
Greg (G-Dog) Reese
Fastball = 40 mph*
= 44 feet/sec
* with strong tailwind
233
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 – ½ gt2
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;
234
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;
235
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)
236
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
237
Writing Functions
Often save result in a variable
Try It
>>
h1
>>
h2
>>
h1
h1 = height(1)
= 25.3465
h2 = height(2)
= 18.6930
h1
= 25.3465
238
Writing Functions
Can see your function over range of values
by using MATLAB function ezplot()
To use:
ez=easy
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
239
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;
240
Writing Functions
V
θ
x
Distance
Distance d that ball travels is
d = v2 sin(2θ) / g
• v is initial speed (velocity)
• g is 32 feet/sec2
• θ is throw angle
241
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 = v2 sin(2θ) / g
function distance = distance( speed )
g = 32; % feet/sec^2
angle = 70; % degrees
distance = ?;
speed^2 * sind(2*angle) / g;
242
Writing Functions
Try It
Store pitcher 1's speed (44 ft/sec) in a
variable and find out how far he threw
the ball
>> speed1 = 44;
>> distance( speed1 )
ans = 38.8887
243
Writing Functions
Pitcher #2
Nolan (The Ryan Express) Ryan
Fastball = over 100 mph* = 147 feet/sec
* even after he turned 40!
244
Writing Functions
Try It
Store pitcher 2's speed (147 ft/sec) in a
variable and find out how far he threw
the ball
>> speed2 = 147;
>> distance( speed2 )
ans = 434.0624
245
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] )
246
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 = v2 sin(2θ)/g
function distance = distance2( speed, angle )
g = 32; % feet/sec^2
distance = speed^2 * sind(2*angle) / g;
247
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
>> distance2(speed1,20)
ans = 38.8887
>> distance2(speed2,20)
ans = 434.0624
>> distance2(speed1,50)
ans = 59.5809
>> distance2(speed2,50)
ans = 665.0222
248
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
249
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] )
250
Writing Functions
Drawbacks
• Have to make another m-file
• When speed changes, have to edit the
m-file
251
Writing Functions
Better solution
Use an anonymous function to
convert distance2 to a function that
accepts only one argument
252
Writing Functions
Anonymous function – a quick way to write a
simple function without having to make an mfile
@(arguments) expression
• arguments – list of arguments separated by
commas
• expression – a single MATLAB expression.
Can be a call of another function!
253
Writing Functions
Try It
"frozen"
expression
>> ezplot( @(angle)distance2(speed1,angle),[0 90] )
varies
anonymous function
254
Writing Functions
>> ezplot( @(angle)distance2(speed1,angle),[0 90] )
255
Writing Functions
Try It
What angle should pitcher 1 throw
the ball at to make it go as far as
possible?
45o
256
Writing Functions
Try It
Repeat for pitcher2
45o
257
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
258
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
259
Writing Functions
In other words…
For the greatest distance throw the ball at a 45o
angle, regardless of how strong your arm is!
260
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
261
Writing Functions
fminbnd finds the minimum of a singlevariable 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
262
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)
263
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
264
Loops
265
Loops
MATLAB has two program structures
that let you execute a set of program
lines repeatedly.
for-loop – executes the set of lines a
given number of times
while-loop – executes the set of lines
while a given condition is true
266
Loops
for var = range
line 1
line 2
...
end
for k = 3:10
f[k] = f[k-1] + f[k-2];
x_power = x_power * x;
fac = fac * k;
end
1. Assign first value of range to var, execute all lines
between for-line and end-line
2. Assign 2nd value of range to var, execute all lines
between for-line and end-line
3. Repeat for each remaining value in range, then go to the
line after the end-line and continue executing the 267
program from there.
Try It
Loops
ex = 1 + x + x2/2! + x3/3! + …
Make a function to compute a given
number of terms of the Taylor series
expansion of ex . The function should
accept x and the number of terms n.
Run it for x = 1 and various values of n
268
Try It
Loops
ex = 1 + x + x2/2! + x3/3! + …
function sum = myexp( x, n )
sum = 1;
for k = 1:n
term = x^k / factorial(k);
sum = sum + term;
end
269
Loops
while( condition )
line 1
line 2
...
end
while( abs(sum-z) > 1e-5 )
sum = sum + 10;
count = count + 1;
fprintf( '%d\n',count );
end
Evaluate the condition
–
–
If it's true, execute all the lines through the end-line and go to the
previous step.
If it's false, go to the line after the end-line and start executing
the program there.
270
Loops
Try It at Home
e-x = 1 – x + x2/2! – x3/3! + …
Make a function to compute the Taylor
series expansion of e-x . Stop adding
terms when you get to one that won't change the
value of the sum
Run it for x = 1
eps is the smallest number in MATLAB that can be
added to another number and change its value
271
Loops
Try It at Home
e-x = 1 – x + x2/2! – x3/3! + …
function sum = while_exp( x )
function
sum
= 1; sum = while_exp( x )
sum =
term
= 1;
-x;term = -x; k = 1;
kwhile(
= 1; abs( term ) > eps )
sum abs(
= sumterm
+ term;
while(
) > eps )
k sum
= k =+ sum
1; + term;
term
k = =k -term
+ 1; * x / k;
end term = -term * x / k;
end
272
Loops
Most important rule about loops
DON'T USE THEM
273
Loops
Handy way to measure time it
takes code to run
• Call tic() immediately before code
• Call toc() immediately after code
tic
operations
toc
where "operations" is a sequence of
MATLAB commands
274
Loops
Try It
Write a function to make one million
normally distributed random numbers by
using a loop. Time the loop
function million_loop
tic;
number = zeros( 1, 1000000 );
for ii=1:1000000
number(ii) = randn( 1, 1 );
end
toc;
275
Loops
Try It
Write a function to make one million
normally distributed random numbers
without using a loop. Time the code
function million_no_loop
tic;
numbers = randn( 1, 1000000 );
toc;
276
Try It
Loops
Compute the ratio of the
slower time to the faster time
>> million_loop
Elapsed time is 1.769582 seconds.
>> million_no_loop
Elapsed time is 0.031329 seconds.
>> 1.769582/0.031329
ans = 56.4838
No-loop is over 50 times faster than loop!
277
Loops
DON'T USE LOOPS
Really means to use built-in functions
or vector/matrix operations if you can
278
Writing Functions
Questions?
279
Workspace
To leave MATLAB
• Type exit or
• Type quit
•
Select File, select Exit
280
The End
281
Download