matlab_introduction

advertisement
MATLAB introduction
Motivation
A fundamental activity of engineering is to describe the world around us
using mathematics. We use mathematical models to describe physical
systems (modeling).
Examples:
• Flow of water through orifice – 1st order differential equation
• Free oscillation of a mass on a spring – 2nd order differential equation
• Current in electrical circuits (RLC) – 2nd order differential equation
• Vibration of circular membrane – Bessel functions
• One-dimensional heat flow – partial differential equation (temperature
depends on both position and time)
MATLAB provides the tools to solve mathematical models in a
programming environment that includes graphing capabilities.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
Start MATLAB by double-clicking on icon or selecting application
from the Start menu. The MATLAB desktop will be launched.
Command prompt “>>”. Can type commands here (or) write and save
your own programs (using m-files). Let’s begin with command prompt.
Type the following and hit Enter.
Command prompt
The variable “a” is assigned (“=”) the value of the square root (“sqrt”) of
243 and the result is echoed to the screen. To clear the variable, use the
“clear a” command. Note that it disappears from the Workspace area.
“clear all” removes all variables
from the Workspace area.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
To clear the text from the Command Window, use “clc”. Next, define an
array (or matrix; MATLAB = matrix laboratory).
http://en.wikipedia.org/wiki/Matrix_(mathematics)
The same 1x5 (row x column) array could be defined as shown.
Default step size is 1.
Command prompt
Individual elements of arrays are identified by their index (or indices). For
a 1xn array, it is only necessary to use the column index since there is
just one row.
Array size is 1x6 (2 rows, 6 columns).
3rd column in “a” is “7”.
Can also access using both indices: (row,
column) = (1, 3).
Command prompt
For mxn arrays (two-dimensional), we must use both the row and column
indices to access individual elements.
Array size is 2x6 (2 rows, 6 columns).
(row, column) = (1, 3) entry is “7”
(row, column) = (2, 5) entry is “15”
To define a 2-row array, we used a semicolon to mark the end of first
row. Both rows must have same number of columns.
Command prompt
An error is generated if the two rows do not have the same number of
columns. “CAT” refers to concatenation (or joining arrays).
Error because there are 6
columns in the 1st row and 7
columns in the 2nd row.
Command prompt
Define array with steps of 0.5 (1x9 array).
Previously defined a row array. Can also define a column array (5x1).
Semicolon marks the end of each row.
Command prompt
Let’s define and add two row arrays.
Square each element of the “a” array.
The “.” tells MATLAB to perform the
squaring operation “^2” term-by-term.
Add the corresponding elements.
The first element of “a” is added to
first element of “b”.
Command prompt
Let’s define and add two other arrays.
Dimensions are: (rows, columns) = (1, 5)
Use the transpose operator (single quote) to
convert row array into column array.
Dimensions are now: (5, 1)
Oops! Arrays must have the same
dimensions to be added.
You can learn more in a Linear Algebra
course.
Command prompt
MATLAB has many functions that
complete specific tasks. My favorite
is “why”. Not very useful, but fun!
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
Let’s define an equation. As an example, consider the volume, V, of a
circular cylinder.
h
V  πr 2h
Use a radius, r, of 8 and a
height, h, of 15.
r
 is defined in MATLAB using “pi”.
Use “*” for multiplication and “^” for power.
3.015910
3
V = 3015.9 (MATLAB uses scientific notation;
value following “e” gives the power of 10).
Command prompt
Given the volume, V, calculate the radius.
r
V
πh
Used the “sqrt” function.
Original “r” value is overwritten
(same value in this case).
Note that when using a semi-colon to end a statement (“r = 8;”), the
assignment is not echoed to the Command Window.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
Can describe polynomials (often used to fit experimental data) by defining
an array of the polynomial coefficients (highest power to lowest).
For a second-order polynomial, we can use the quadratic equation to
determine the two roots (x values where y(x) = 0).
y  ax  bx  c
2
x1,2
 b  b2  4ac

2a
MATLAB has a function “roots” that can be used to find the roots of nthorder polynomials.
Consider the example:
x1,2
y  1x2  15x  50
 15  152  4 1 50  15  5


2 1
2 1
x1  5
Let’s complete the same example using MATLAB.
x 2  10
Command prompt
Use indices of array to call specific value;
a = y(1), b = y(2), c = y(3).
y  ax2  bx  c  1x2  15x  50
Used the “roots” command to find two
values of x where y(x) = 0. Same result
as quadratic equation.
Command prompt
y  1x3  7x2  40x - 34
Can also separate elements of row array
using commas rather than spaces.
The roots are:
x1,2  3  5i
x3  1
( i  1)
Command prompt
y  5x 4  110x2  200
y  5x4  0x3  110x2  0x  200
The roots are: x1,2   20  i
x1,2   2  i



y  5x4  110x2  200  5x2  10 x2  20  0
Can factor this
polynomial to
x 2  20
x 2  2
check the result:
Command prompt
Let’s look more closely at accessing
individual elements of arrays using indices.
Step size is -2.
3
ba
The “.^3” gives the term-by-term cube.
The first element of “a” is 10.
The first element of “b” is:
b1  a1  10  1000
3
3
Command prompt
If the “.^” operator is not used, we get an error. This is because the “^3” is
attempting to perform: “a*a*a”. The “^” operator requires square arrays;
this means that the number of rows and columns must be equal (mxm
arrays).
Command prompt
We can also access ranges of elements.
This lists the 5th to 8th elements
of “a” and “b”.
b8  a8  - 4  -64
3
3
Command prompt
The “find” function is used to identify the indices (not values) of particular
elements. It can be used with the relational operators: >, >=, <, <=, ==, ~=.
The “;” suppresses output to Command
Window for “a”.
Find indices of all “b” values > 0.
This is the first 5 elements of “b”.
Show “b” values with indices of 1 through 5.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
Consider the cosine function:
y  5 cosx 
First, define x and then calculate y.
2π
Step size in x is:
10
Range is -2 to 2.
Trigonometric functions require inputs in
radians ( rad = 180 deg), not degrees, for
MATLAB.
In this case, it would be better to graph the data to see the result. Use the
“plot” function to graph (x, y) data.
Command prompt
Figure
window
5
4
3
2
1
y
Individual points are
connected by line segments.
0
The x axis limits are set
between -2 and 2 using
“xlim”.
-1
Let’s plot only the points
next; no line segments.
-4
-2
-3
-5
Set using
“xlabel”.
-6
- 2π
-4
-2
0
x
2
4
6
2π
Command prompt
Many figure windows can be opened at the same time (1, 2, 3, …).
Command prompt
5
4
3
We might like to have higher
resolution in x values so the
points are closer together
and the cosine function is
“smoother” when graphed.
2
1
y
Now only the (x, y) points
are shown – red circles are
specified by “ro”.
0
-1
2π
x step size
10
-2
-3
-4
-5
-6
-4
-2
0
x
2
4
6
Command prompt
5
4
3
2
1
y
2π
Step size in x is now:
100
0
-1
Graph looks more continuous.
-2
-3
-4
-5
-6
-4
-2
0
x
2
4
6
Command prompt
5
y1
4
y2
3
2
Can plot multiple curves in the
same graph. Used blue squares
for y1 (larger step size in x1) and
red line for y2.
Added “legend” to identify two
different curves on single plot.
y
1
0
-1
-2
-3
-4
-5
-6
-4
-2
0
x
2
4
6
Command prompt
Type “help plot”
to learn more.
‘bs’ = blue square
‘r^’ = red triangle (pointing up)
‘k:’ = black dotted line
Command prompt
1.5708
1.5708
Plot “a + b”.
1.5708
Let’s use the plotting
function to verify identities.
π
sin -1 x   cos -1 x  
2
a  sin x
-1
a+b
1.5708
π
 1.5708
2
1.5708
1.5708
2π
x step size
10
1.5708
b  cos x 
-1
1.5708
1.5708
1.5708
-6
-4
-2
0
x
2
4
6
Command prompt
Use “exp” function for exponential.
300
250
coshx  
a  ex
e e
2
x
x
coshx 
200
(a + b)/2
Let’s again use the plotting
function to verify identities.
b  e-x
(a + b)/2
150
100
50
Plot (a + b)/2 and compare to cosh.
0
-6
-4
-2
0
x
2
4
6
Command prompt
(x, y) = (0, 3)
20
0
y
51st y element
-20
-40
-60
Find the maximum value of y
using “max”.
2
y  -4x  3
-80
-100
-5
-4
-3
-2
-1
0
x
1
2
3
4
5
Command prompt
20
0
y
-20
y  ax2  bx  c  -4x2  0x  3
Roots are x = 0.866, -0.866.
-40
-60
-80
-100
-5
-4
-3
-2
-1
0
x
1
2
3
4
5
Command prompt
y  4x2  3
120
100
y
80
60
(x, y) = (0, 3)
40
20
Find minimum using “min”.
0
-5
-4
-3
-2
-1
0
x
1
2
3
4
5
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Command prompt
Can use MATLAB to solve systems of linear equations.
2x1  9x 2  5
3x1  4x 2  7
Write in vectormatrix form.
2 9   x1  5 
3 - 4   x   7 

 2   
Vector-matrix form can be represented compactly as: Ax = b
2 9 
A

3
4


 x1 
x 
x 2 
5
b 
7
Can determine x using the inverse of the A matrix: x = A-1b
Perform this operation in MATLAB.
1
 x1  2 9  5
 x   3 - 4 7
  
 2 
Command prompt
Define the “A” matrix. Note the use of the
semicolon to give the 2nd row.
The “inv” function calculates the inverse
of a square matrix (the number of rows is
equal to the number of columns).
This is more Linear Algebra.
2.3714
x

0.0286
Check this
result.
2x1  9x 2  5
3x1  4x 2  7
22.3714  90.0286  5
32.3714  40.0286  7
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
M-file
Rather than typing at the command prompt (>>), can write a program to
execute series of commands. This is an m-file in MATLAB.
Click to begin new m-file.
The Editor screen is launched. We can now type commands
in a single program (saved as _____.m) and execute this new
program when we are ready.
M-file
Let’s write a program (tank.m) to solve the following problem.
A water tank consists of a cylindrical base of radius r and height h and
has a hemispherical top (also radius r). The tank is to be constructed to
hold V = 500 m3 of fluid when filled. The surface area of the cylindrical
part is 2rh and its volume is r2h. The surface area of the hemispherical
top is 2r2 and its volume is 2r3/3.
The cost to construct the cylindrical part of the tank is $300/m2 of surface
area; the hemispherical part costs $400/m2. Plot the cost versus r for 2  r
 10 m and determine the radius that results in the minimum cost.
Compute the corresponding height h.
r
2π  r 3
V
3
h
π r2

C  3002π  rh  400 2π  r 2

h
M-file
Click to execute the m-file. This
also saves the program.
Define step/range for r.
“h” is an array. Must use “.” for
term-by-term power and division.
Same for “C”.
Find the index of “C” where it is
equal to its minimum value.
“%” for
comments.
Determine “r”, “h”, and “C” at this
index.
Plot “C” as function of “r”.
Note that you need to have your m-file in the current directory to
execute it.
M-file
5
1.6
x 10
1.5
cost ($)
1.4
The minimum cost is $91394
for a radius of 4.92 m and
height of 3.2949 m.
1.3
1.2
(4.92, 91394)
1.1
1
0.9
2
3
4
5
6
radius (m)
7
8
9
10
M-file
The aorta is the largest artery in the body, originating from
the left ventricle of the heart and bringing oxygenated blood
to all parts of the body in the systemic circulation. The
aorta extends down to the abdomen, where it branches off
into two smaller arteries.
The blood pressure in the aorta during
systole (the period following the closure
of the heart’s aortic valve) can be
described using:


yt   e-8t sin 9.7t  
2

http://en.wikipedia.org/wiki/Aorta
where t is time in seconds and y(t) is
the pressure difference across the
aortic valve, normalized by a constant
reference pressure (y is unitless).
M-file
100 steps per cycle


yt   e sin 9.7t  
2

-8t
Use “.*” for element-byelement multiplication
because t is an array.
This is an oscillating function (sine wave)
that decays exponentially. We must
decide on step size to plot the function.
9.7
 1.54 cycles/s (Hz).
2π
1
1

 0.648 s.
The time for one full cycle (or period) is:
f 1.54
Oscillating frequency is 9.7 rad/s. This is: f 
M-file
1.2
5 steps
per cycle
1
0.8
0.6
y(t)
100 steps
per cycle
0.4
0.2
0
Red square with dotted line
-0.2
0
0.05
0.1
0.15
0.2
0.25
0.3
time (s)
0.35
0.4
0.45
0.5
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Decision-making
The usefulness of computer programs is
increased by using decision-making
functions. This enables operations to be
completed that depend on the results of
calculations.
The relational operators make comparisons
between arrays.
The result of using relational operators is 1 if
true and 0 if false.
56
False = 0
5  5
True = 1
5 ~ 5
False = 0
operator
meaning
<
Less than
<=
Less than or
equal to
>
Greater than
>=
Greater than
or equal to
==
Equal to
~=
Not equal to
Can compare arrays in element-byelement fashion. Let’s consider some
examples…
Decision-making
x = [6 3 9]
x = [6 3 9]
y = [14 2 9]
y = [14 2 9]
9<9, false = 0
6<14, true = 1
Decision-making
x = [6 3 9]
x = [6 3 9]
y = [14 2 9]
y = [14 2 9]
9~=9, false = 0
6~=14, true = 1
Decision-making
Can also compare arrays to a scalar.
x = [6 3 9]
x = [6 3 9]
8
9>8, true = 1
6>8, false = 0
8
Decision-making
The logical operators also make comparisons between arrays. The result of
using logical operators is again 1 if true and 0 if false.
operator
name
definition
~
NOT
“~A” returns an array with the same dimensions as
“A”; the new array has ones where “A” is zero and
zeros where “A” is nonzero
&
AND
“A&B” returns an array the same dimensions as “A”
and “B”; the new array has ones where both “A”
and “B” have nonzero elements and zeros where
either “A” or “B” is zero
|
OR
“A|B” returns an array the same dimensions as “A”
and “B”; the new array has ones where either “A”
and “B” have nonzero elements and zeros where
both “A” or “B” is zero
Look at some examples in MATLAB…
Decision-making
z = ~x = ~[0 3 9]
~x(3) = ~9 = 0
~x(1) = ~0 = 1
NOT
“~A” returns an array with the same dimensions
as “A”; the new array has ones where “A” is zero
and zeros where “A” is nonzero
Decision-making
z = ~x > y = ~[0 3 9] > [14 -2 9]
~x = ~[0 3 9] = [1 0 0]
1 > 14, false = 0
0 > -2, true = 1
NOT
z = [1 0 0] > [14 -2 9]
Decision-making
z = ~(x > y) = ~([0 3 9] > [14 -2 9])
[0 3 9] > [14 -2 9]
[0>14
NOT
3>-2
9>9]
[0
1
0]
~[0
1
0]
Decision-making
z=0&3=0
“A&B” returns an array the same dimensions as
“A” and “B”; the new array has ones where both
“A” and “B” have nonzero elements and zeros
where either “A” or “B” is zero
z=2&3=1
AND
Decision-making
“z” has same dimensions as “x”
and “y”
5 & 2, true = 1
AND
0 & 5, false = 0
Decision-making
“x” dimensions are 1x4
“y” dimensions are 1x5
AND
“x&y” gives error
Decision-making
z=0|3=1
“A|B” returns an array the same dimensions as “A”
and “B”; the new array has ones where either “A”
and “B” have nonzero elements and zeros where
both “A” or “B” is zero
z=2|3=1
OR
Decision-making
“z” has same dimensions as “x”
and “y”
5 | 2, true = 1
0 | 5, true = 1
0 | 0, false = 0
OR
Decision-making
These results are typically summarized in a truth table.
NOT, AND, OR
x
y
~x
x|y
x&y
T
T
F
T
T
T
F
F
T
F
F
T
T
T
F
F
F
T
F
F
Decision-making
We already introduced the “find” function. “find(x)” is used to compute an
array containing the indices (not values) of the nonzero elements of “x”.
x = [-2 0 4]
y = find(x)
Nonzero “x” elements
are “-2” and [4]
x(1) = -2, nonzero
x(y) = [-2 4]
x(2) = 0
x(3) = 4, nonzero
y = [1 3]
1st element of x is
nonzero; index is 1
for 1st element
3rd element of x is
nonzero; index is 3
for 3rd element
Decision-making
x = [6 3 9 11]
y = [14 2 9 13]
index = find(x < y)
This finds the indices of the
comparison (x < y) where the values
are true (1).
x = [6 3 9 11]
6<14
3<2
True
False
y = [14 2 9 13]
9<9
11<13
False
True
“find” returns the indices 1 and 4
where the comparison is true (1)
Decision-making
x = [5 -3 0 0 8]
y = [2 4 0 5 7]
5&2 -3&4
0&0
0&5
8&7
True True False False True
“find” returns the indices 1, 2, and 5
where the comparison is true (1)
x([1 2 5]) = [5 -3 8]
y([1 2 5]) = [2 4 7]
Decision-making
Consider a projectile that is launched with a speed v0 at an angle A
(relative to the horizontal). Its height, h, and velocity, v, depend on the time
since launch (at t = 0).
v(t)
v0
A
h(t)
ht   v 0 t sinA   0.5gt 2
v t   v 0 2v 0 gt sinA   g2 t 2
2
The time is takes to hit the ground is obtained
by setting h(t) = 0 and solving for the time, thit.
t hit
v 0 sinA 

0.5g
Decision-making
Let v0 = 20 m/s and A = 40 deg (g = 9.81 m/s2). Find the times (between t =
0 and thit) when the height is no less than 6 m and the speed is
simultaneously no greater than 16 m/s.
v <= 16 m/s
v0
A
h>=6m
Solve for v and h as a function of time. Use relational and logical operators
to find times when height and velocity conditions are both true.
Need to select step size for t. Choose thit/100.
Write program (m-file) to complete this task. Plot v and h versus t to check
results.
Decision-making
Use “find” to determine indices of
time where h >= hlim and v <= vlim.
Define “t_true” where conditions are
satisfied using “index”.
Find first and last values of “t_true”.
Use “subplot” to make figure with
2x1 panels. Plot lines at hlim and
vlim using “line” function.
Decision-making
Find the times (between t = 0 and thit) when the height is no less than 6 m
and the speed is simultaneously no greater than 16 m/s.
10
h(t)
8
6
4
2
0
0
0.5
1
1.5
2
2.5
20
For the specified conditions,
the velocity limits the range.
v(t)
19
t1 = 0.8649 s
18
t2 = 1.7560 s
17
16
15
0
0.5
1
1.5
time (s)
2
2.5
Decision-making
The conditional statements if, else, and elseif also enable decision-making
in programs.
if logical expression
The basic structure of the if statement is:
statements
end
Consider the case that it is only desired to calculate the square root of x if
x is greater than or equal to zero. The logic is: if x >= 0, then calculate y =
sqrt(x). If x is negative, take no action.
if x >= 0
y = sqrt(x);
end
if statements may
also be nested.
There can be multiple statements within
the if statement. There is only one (y =
sqrt(x);) here, however.
if logical expression 1
if logical expression 2
statements
end
end
Decision-making
When more than one action can occur as the result of a decision, use else
and elseif statements along with the if statement.
if logical expression
statements 1
The basic structure of the else statement is:
else
statements 2
end
Consider the case that y = sqrt(x) for x >= 0 and that y = ex-1 for x < 0.
if x >= 0
y = sqrt(x);
else
y = exp(x) – 1;
end
Decision-making
The elseif statement enables an additional decision to be made with an if
statement.
The basic structure of the elseif statement is:
Consider the case that y = ln(x) for x > 10,
y = sqrt(x) for 0 <= x <= 10, and y = ex-1
for x < 0.
y  ln x ,
y  x,
y  e x  1,
if x > 10
x  10
0  x  10
x0
if logical expression 1
statements 1
elseif logical expression 2
statements 2
else
statements 3
end
If not true, then
x is <= 10.
y = log(x);
elseif x >= 0
If not true, then
y = sqrt(x);
x is < 0.
else
y = exp(x) – 1;
end
Decision-making
Consider the previous example and write an m-file to determine the result
based on the selected x value.
Request “x” value from the user.
Calculate “y” based on “x” input.
Display text and “y” to Command Window.
Decision-making
x  10
y  lnx 
0  x  10 y  x
x0
y  ex  1
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Loops
A loop is a structure used to repeat a calculation (or group of statements)
a number of times. The for loop is used when the number of repetitions is
known beforehand. The while loop is used when the loop continues until a
specified condition is satisfied.
for counter = m:s:n
statements
end
“m” is the starting value of the loop counter
“s” is the step size of the counter
“n” is the final value of the loop counter
Example: Write an m-file to compute the sum of the first 15 terms of the
series 5k2 – 2k, where k = 1, 2, 3…
Use a for loop to complete the task.
Loops
Initialize “total” value to zero.
Loop counter is “k”. Update “total” value
each repetition.
Display results in
Command Window.
Loops
Free vibration of a single degree of freedom spring-mass-damper system
can be expressed as:


 - x  ζω x 
x0
 ζωn t
2

1
0
n 0 
xt  
e
cos ωn 1 ζ  t  φ where φ  tan 
cosφ
 ω 1 ζ 2  x 
0 
 n
c
k
ζ
ωn 
2 km
m
c = 50
N-s/m
k = 1106
N/m
x(t)
m = 2 kg
x0  x0
Initial displacement of mass
from equilibrium position
x 0  x 0
Initial velocity of mass
Let initial displacement be 5 mm = 0.005 m and initial velocity be zero.
Write m-file to plot x(t) in time steps of 0.0001 s for 0.5 s.
Loops
Use “round” to round
number of repetitions
to nearest integer.
Use counter “cnt” to index “t”
and “x” and write arrays.
Loops
Exponentially decaying
cosine wave.
Converted “x” from m to mm.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Polynomial fitting
We use mathematical models to describe physical systems (modeling).
This often takes the form of collecting data and fitting a function, such as a
polynomial, to the data.
Regression analysis is finding the polynomial that best fits the data in a
least squares sense.
Example: Fit x/y data with a line (1st order polynomial)
x
y
0
2
5
6
10
11
y  mx  b
Find m and b for least squares
best fit to values of y (dependent
variable) at x locations
(independent variable).
Best fit is provided by the line that minimizes the sum of the squares in the
vertical (y-direction) differences between the line and data points. These
differences are the residuals.
Polynomial fitting
The sum of the squares of the residuals is:
3
J   mx i  b - yi   m  0  b - 2  m  5  b - 6  m 10  b - 11
2
2
2
2
i1
Values of m and b that minimize J are found from:
J
0
m
J
0
b
J  125m2  30mb  280m  3b2  38b  161
J
 250m  30b  280  0
m
J
 30m  6b  38  0
b
Write in vector-matrix form:
250 30 m 280
 30 6   b    38 

  

Determine [m b]T using the inverse of the 2x2 matrix. Perform this
operation in MATLAB.
Polynomial fitting
Solve for m and b:
The best fit line is:
1
m 250 30 280
 b    30
  38 
6
  
 

m = 0.9
x
y
b = 1.8333
0
2
5
6
10
11
y fit  0.9x  1.8333
Find J – the sum of the squares of the residuals.
Polynomial fitting
Find J from the residuals.
y fit  0.9x  1.8333
No other straight line will give a
smaller J.
x
y
yfit
(yfit-yi)2
0
2
1.8333
0.0278
5
6
6.3333
0.1111
10
11
10.833
0.0278
J  0.1667
y fit  0.9x  1.8333
Polynomial fitting
11
data
10
fit
9
8
y
7
Minimized vertical
distance (residual) using
least squares fitting.
6
5
4
3
2
1
0
1
2
3
4
y fit  0.9x  1.8333
5
x
6
7
8
9
10
x
y
0
2
5
6
10
11
Polynomial fitting
MATLAB can complete this task using the function “polyfit”. The format for
the function call is:
x – independent variable
p = polyfit(x, y, n)
y – dependent variable
n – order of the polynomial fit
p – row array that contains the polynomial
coefficients in descending powers
Example: Fit x/y data with line (1st order polynomial)
x
y
0
2
5
6
10
11
y  a1x  a2
Find a1 and a2 for least squares
best fit to values of y (dependent
variable) at x locations
(independent variable).
Polynomial fitting
p – row array that contains the polynomial
coefficients in descending powers
y  a1x  a2
Best fit line
3
J   a1xi  a2 - yi 
2
i1
x
y
yfit
(yfit-yi)2
0
2
1.8333
0.0278
5
6
6.3333
0.1111
10
11
10.833
0.0278
Polynomial fitting
Example: Bacterial growth
Bacterial growth is the division
of one bacterium into two
daughter cells in a process
called binary fission. Providing
no mutational event occurs, the
resulting daughter cells are
genetically identical to the
original cell. Hence, "local
doubling" of the bacterial
population occurs. Both
daughter cells from the division
do not necessarily survive.
http://en.wikipedia.org/wiki/Bacterial_growth
Video
http://www.youtube.com/watch?v=gEwzDydciWc
t (min)
Bacteria
(ppm)
t (min)
Bacteria
(ppm)
0
6
10
350
1
13
11
440
2
23
12
557
3
33
13
685
4
54
14
815
5
83
15
990
6
118
16
1170
7
156
17
1350
8
210
18
1575
9
282
19
1830
Polynomial fitting
1st order fit to data
Best fit line
19
J   a1t i  a2 - bacteriai 
i1
2
Polynomial fitting
Large residuals with structure
Polynomial fitting
2nd order fit to data
Best fit quadratic
19

J   a1t i  a2 t i  a3 - bacteriai
i1
2

2
Polynomial fitting
Residuals reduced, but some structure remains.
Polynomial fitting
3rd order fit to data
Best fit cubic
19

J   a1t i  a2 t i  a3 t  a4 - bacteriai
i1
3
2

2
Polynomial fitting
Smallest residuals with little structure.
Polynomial fitting
2000
500
0
2
4
6
8
10
12
14
16
18
500
1500
2
4
6
8
10
12
14
16
18
20
-200
-400
0
2
4
6
8
10
12
time (min)
14
16
18
20
50
0
-50
-100
0
2
4
6
8
0
2
4
6
8
10
12
14
16
18
20
10
12
time (min)
14
16
18
20
10
residual (ppm)
0
500
0
0
fit
1000
100
200
residual (ppm)
residual (ppm)
fit
1000
0
20
400
-600
1500
bacteria (ppm)
bacteria (ppm)
bacteria (ppm)
1000
0
data
data
fit
-500
2000
2000
data
1500
5
0
-5
-10
-15
0
2
4
6
8
10
12
time (min)
14
16
18
20
1st order fit
2nd order fit
3rd order fit
J = 7.9736x105
J = 1.6776x104
J = 580.936 ppm
Best fit for this
data set
Summary
• Examined basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
More information is available from: William J. Palm III, A Concise
Introduction to MATLAB, McGraw-Hill, 2008.
Download