Upload
emory
View
22
Download
4
Tags:
Embed Size (px)
DESCRIPTION
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 – 1 st order differential equation - PowerPoint PPT Presentation
Citation preview
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. MATLAB R2006a.lnk
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).
The same 1x5 (row x column) array could be defined as shown.
Default step size is 1.
http://en.wikipedia.org/wiki/Matrix_(mathematics)
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.
3rd column in “a” is “7”.
Can also access using both indices: (row, column) = (1, 3).
Array size is 1x6 (2 rows, 6 columns).
Command prompt
For mxn arrays (two-dimensional), we must use both the row and column indices to access individual elements.
(row, column) = (1, 3) entry is “7”
(row, column) = (2, 5) entry is “15”
Array size is 2x6 (2 rows, 6 columns).
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.
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
Command prompt
Previously defined a row array. Can also define a column array (5x1).
Define array with steps of 0.5 (1x9 array).
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.
Use the transpose operator (single quote) to convert row array into column array.
Oops! Arrays must have the same dimensions to be added.
You can learn more in a Linear Algebra course.
Dimensions are: (rows, columns) = (1, 5)
Dimensions are now: (5, 1)
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.
r
h
hπrV 2
V = 3015.9 (MATLAB uses scientific notation; value following “e” gives the power of 10).
is defined in MATLAB using “pi”.
Use “*” for multiplication and “^” for power.
Use a radius, r, of 8 and a height, h, of 15.
3103.0159
Given the volume, V, calculate the radius.
Command prompt
πh
Vr
Note that when using a semi-colon to end a statement (“r = 8;”), the assignment is not echoed to the Command Window.
Used the “sqrt” function.
Original “r” value is overwritten (same value in this case).
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
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).
Command prompt
cbxaxy 2 2a
4acbbx
2
1,2
MATLAB has a function “roots” that can be used to find the roots of nth-order polynomials.
Consider the example: 5015x1xy 2
12
515
12
50141515x
2
1,2
5x1 10x2
Let’s complete the same example using MATLAB.
Use indices of array to call specific value; a = y(1), b = y(2), c = y(3).
Used the “roots” command to find two values of x where y(x) = 0. Same result as quadratic equation.
5015x1xcbxaxy 22
Command prompt
Can also separate elements of row array using commas rather than spaces.
34-40x7x1xy 23
The roots are: ( ) 5i3x1,2 1x3
Command prompt
1i
Command prompt
200110x5xy 24
2000x110x0x5xy 234
The roots are: i20x1,2
i2x1,2
Can factor this polynomial to check the result:
020x105x200110x5xy 2224
2x2 20x2
Command prompt
Let’s look more closely at accessing individual elements of arrays using indices.
3ab
The first element of “a” is 10.
The first element of “b” is:
1000101a1b 33
Step size is -2.
The “.^3” gives the term-by-term cube.
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”.
-644-8a8b 33
Command prompt
The “find” function is used to identify the indices (not values) of particular elements. It can be used with the relational operators: >, >=, <, <=, ==, ~=.
Find indices of all “b” values > 0.
This is the first 5 elements of “b”.
Show “b” values with indices of 1 through 5.
The “;” suppresses output to Command Window for “a”.
Outline
• Examine basic commands typed at the command prompt
• Arrays
• Equations
• Polynomials
• Plotting
• Systems of equations
• M-files
• Decision-making
• Loops
• Polynomial fitting
Consider the cosine function:
Command prompt
xcos 5y
First, define x and then calculate y.
In this case, it would be better to graph the data to see the result. Use the “plot” function to graph (x, y) data.
Step size in x is:10
2πRange is -2 to 2.
Trigonometric functions require inputs in radians ( rad = 180 deg), not degrees, for MATLAB.
Command prompt
-6 -4 -2 0 2 4 6-5
-4
-3
-2
-1
0
1
2
3
4
5
x
y
Individual points are connected by line segments.
The x axis limits are set between -2 and 2 using “xlim”.
Let’s plot only the points next; no line segments.
2π- 2π
Set using “xlabel”.
Figure window
Command prompt
Many figure windows can be opened at the same time (1, 2, 3, …).
-6 -4 -2 0 2 4 6-5
-4
-3
-2
-1
0
1
2
3
4
5
x
yNow only the (x, y) points are shown – red circles are specified by “ro”.
We might like to have higher resolution in x values so the points are closer together and the cosine function is “smoother” when graphed.
10
2π
Command prompt
x step size
Command prompt
-6 -4 -2 0 2 4 6-5
-4
-3
-2
-1
0
1
2
3
4
5
x
yStep size in x is now:100
2π
Graph looks more continuous.
Command prompt
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.
-6 -4 -2 0 2 4 6-5
-4
-3
-2
-1
0
1
2
3
4
5
x
y
y1
y2
Command prompt
Type “help plot” to learn more.
‘bs’ = blue square
‘r^’ = red triangle (pointing up)
‘k:’ = black dotted line
Command prompt
Let’s use the plotting function to verify identities.
2
πxcosxsin 1-1-
xsin a -1 xcos b -1
-6 -4 -2 0 2 4 61.5708
1.5708
1.5708
1.5708
1.5708
1.5708
1.5708
1.5708
1.5708
1.5708
x
a +
b
1.57082
π
Plot “a + b”.
10
2πx step size
Let’s again use the plotting function to verify identities.
2
eexcosh
xx
xe a
-6 -4 -2 0 2 4 60
50
100
150
200
250
300
x
(a +
b)/
2
-xe b
Use “exp” function for exponential.
Command prompt
Plot (a + b)/2 and compare to cosh.
xcosh
(a + b)/2
Command prompt
-5 -4 -3 -2 -1 0 1 2 3 4 5-100
-80
-60
-40
-20
0
20
x
y
Find the maximum value of y using “max”.
3-4xy 2
(x, y) = (0, 3)
51st y element
-5 -4 -3 -2 -1 0 1 2 3 4 5-100
-80
-60
-40
-20
0
20
x
y
30x-4xcbxaxy 22
Roots are x = 0.866, -0.866.
Command prompt
Command prompt
-5 -4 -3 -2 -1 0 1 2 3 4 50
20
40
60
80
100
120
x
y
(x, y) = (0, 3)
34xy 2
Find minimum using “min”.
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.
74x3x
59x2x
21
21
Write in vector-
matrix form.
7
5
x
x
4-3
92
2
1
Vector-matrix form can be represented compactly as: Ax = b
4-3
92A
2
1
x
xx
7
5b
Can determine x using the inverse of the A matrix: x = A-1b
Perform this operation in MATLAB.
7
5
4-3
92
x
x1
2
1
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.
70.028642.37143
50.028692.37142
0.0286
2.3714x Check this
result. 74x3x
59x2x
21
21
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 2rh and its volume is r2h. The surface area of the hemispherical top is 2r2 and its volume is 2r3/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.
h
r
2
3
πr3
r2πV
h
2r2π400rh2π300C
M-file
“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.
Determine “r”, “h”, and “C” at this index.
Plot “C” as function of “r”.
Define step/range for r.
Click to execute the m-file. This also saves the program.
Note that you need to have your m-file in the current directory to execute it.
“%” for comments.
M-file
2 3 4 5 6 7 8 9 100.9
1
1.1
1.2
1.3
1.4
1.5
1.6x 10
5
radius (m)
cost
($)
The minimum cost is $91394 for a radius of 4.92 m and height of 3.2949 m.
(4.92, 91394)
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.
http://en.wikipedia.org/wiki/Aorta
The blood pressure in the aorta during systole (the period following the closure of the heart’s aortic valve) can be described using:
29.7tsinety 8t-
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
29.7tsinety 8t-
This is an oscillating function (sine wave) that decays exponentially. We must decide on step size to plot the function.
Oscillating frequency is 9.7 rad/s. This is: 1.542π
9.7f cycles/s (Hz).
The time for one full cycle (or period) is: 0.6481.54
1
f
1 s.
100 steps per cycle Use “.*” for element-by-element multiplication because t is an array.
M-file
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5-0.2
0
0.2
0.4
0.6
0.8
1
1.2
time (s)
y(t) 100 steps
per cycle
5 steps per cycle
Red square with dotted line
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.
operator meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
65
55
55 ~
False = 0
True = 1
False = 0
Can compare arrays in element-by-element fashion. Let’s consider some examples…
Decision-making
6<14, true = 1
x = [6 3 9] y = [14 2 9]
9<9, false = 0
x = [6 3 9] y = [14 2 9]
Decision-making
6~=14, true = 1
x = [6 3 9] y = [14 2 9]
9~=9, false = 0
x = [6 3 9] y = [14 2 9]
Decision-making
6>8, false = 0
x = [6 3 9] 8
9>8, true = 1
x = [6 3 9] 8
Can also compare arrays to a scalar.
The logical operators also make comparisons between arrays. The result of using logical operators is again 1 if true and 0 if false.
Decision-making
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(1) = ~0 = 1
~x(3) = ~9 = 0
“~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
NOT
Decision-making
z = ~x > y = ~[0 3 9] > [14 -2 9]
~x = ~[0 3 9] = [1 0 0]
z = [1 0 0] > [14 -2 9]1 > 14, false = 0
0 > -2, true = 1
NOT
Decision-making
z = ~(x > y) = ~([0 3 9] > [14 -2 9])
[0 3 9] > [14 -2 9]
[0>14 3>-2 9>9]
[0 1 0]
~[0 1 0]
NOT
Decision-making
AND
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
Decision-making
AND
5 & 2, true = 1 0 & 5, false = 0
“z” has same dimensions as “x” and “y”
Decision-making
“x” dimensions are 1x4“y” dimensions are 1x5
“x&y” gives error
AND
Decision-making
OR
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
Decision-making
5 | 2, true = 1 0 | 5, true = 1
“z” has same dimensions as “x” and “y”
0 | 0, false = 0
OR
Decision-making
These results are typically summarized in a truth table.
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 FNOT, AND, OR
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)
x(1) = -2, nonzero
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
x(y) = [-2 4]
Nonzero “x” elements are “-2” and [4]
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] y = [14 2 9 13]6<14 3<2 9<9 11<13True False 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&7True 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).
v0
Ah(t)
v(t)
22
02
0
20
tgAsin gt2vvtv
0.5gtAsin tvth
The time is takes to hit the ground is obtained by setting h(t) = 0 and solving for the time, thit.
0.5g
Asinvt 0
hit
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.
v0
Ah > = 6 m
v <= 16 m/s
Decision-making
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.
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.
0 0.5 1 1.5 2 2.50
2
4
6
8
10
h(t)
0 0.5 1 1.5 2 2.515
16
17
18
19
20
time (s)
v(t)
t1 = 0.8649 s t2 = 1.7560 sFor the specified conditions, the velocity limits the range.
Decision-making
Decision-making
The conditional statements if, else, and elseif also enable decision-making in programs.
The basic structure of the if statement is:if logical expression
statementsend
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 >= 0y = sqrt(x);
end
There can be multiple statements within the if statement. There is only one (y = sqrt(x);) here, however.
if logical expression 1if logical expression 2
statementsend
end
if statements may also be nested.
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.
The basic structure of the else statement is:
if logical expressionstatements 1
elsestatements 2
end
Consider the case that y = sqrt(x) for x >= 0 and that y = ex-1 for x < 0.
if x >= 0y = sqrt(x);
elsey = 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:
if logical expression 1statements 1
elseif logical expression 2statements 2
elsestatements 3
end
Consider the case that y = ln(x) for x > 10, y = sqrt(x) for 0 <= x <= 10, and y = ex-1 for x < 0.
if x > 10y = log(x);
elseif x >= 0y = sqrt(x);
elsey = exp(x) – 1;
end
If not true, then x is <= 10.
If not true, then x is < 0.
1,ey
,xy
,xlny
x
0x
10x0
10x
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
xlny 10x
xy 10x0
1ey x 0x
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:nstatements
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
Loop counter is “k”. Update “total” value each repetition.
Initialize “total” value to zero.
Display results in Command Window.
Loops
Free vibration of a single degree of freedom spring-mass-damper system can be expressed as:
φtζ1ωcoseφcos
xtx 2
ntζω0 n
02
n
0n01
xζ1ω
xζωx-tanφ
where
m = 2 kg
k = 1106
N/m
x(t)
c = 50 N-s/m
m
kωn
km2
cζ
0xx0 Initial displacement of mass from equilibrium position
0xx0 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
bmxy 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:
2223
1i
2ii 11-b10m6-b5m2-b0my-bmxJ
Values of m and b that minimize J are found from: 0m
J
0b
J
16138b3b280m30mb125mJ 22
028030b250mm
J
0386b30mb
J
Write in vector-matrix form:
38
280
b
m
630
30250
Determine [m b]T using the inverse of the 2x2 matrix. Perform this operation in MATLAB.
Polynomial fitting
Solve for m and b:
38
280
630
30250
b
m1
m = 0.9
b = 1.8333
The best fit line is: 1.83330.9xy fit
x y
0 2
5 6
10 11
Find J – the sum of the squares of the residuals.
Polynomial fitting
Find J from the residuals.
1.83330.9xy fit x y yfit (yfit-yi)2
0 2 1.8333 0.0278
5 6 6.3333 0.1111
10 11 10.833 0.0278
0.1667J
No other straight line will give a smaller J.
1.83330.9xy fit
0 1 2 3 4 5 6 7 8 9 101
2
3
4
5
6
7
8
9
10
11
x
y
data
fit
Polynomial fitting
Minimized vertical distance (residual) using least squares fitting.
x y
0 2
5 6
10 11
1.83330.9xy fit
Polynomial fitting
MATLAB can complete this task using the function “polyfit”. The format for the function call is:
p = polyfit(x, y, n)x – independent variable
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
21 axay Find a1 and a2 for least squares best fit to values of y (dependent variable) at x locations (independent variable).
Polynomial fitting
21 axay
p – row array that contains the polynomial coefficients in descending powers
x y yfit (yfit-yi)2
0 2 1.8333 0.0278
5 6 6.3333 0.1111
10 11 10.833 0.0278
3
1i
2i2i1 y-axaJ
Best fit line
Polynomial fitting
Example: Bacterial growth
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 1830http://www.youtube.com/watch?v=gEwzDydciWc
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
Polynomial fitting
1st order fit to data
19
1i
2i2i1 bacteria-ataJ
Best fit line
Polynomial fitting
Large residuals with structure
Polynomial fitting
2nd order fit to data
19
1i
2
i3i22
i1 bacteria-atataJ
Best fit quadratic
Polynomial fitting
Residuals reduced, but some structure remains.
Polynomial fitting
3rd order fit to data
19
1i
2
i432
i23i1 bacteria-atatataJ
Best fit cubic
Polynomial fitting
Smallest residuals with little structure.
Polynomial fitting
0 2 4 6 8 10 12 14 16 18 20-500
0
500
1000
1500
2000
bact
eria
(pp
m)
data
fit
0 2 4 6 8 10 12 14 16 18 20-600
-400
-200
0
200
400
time (min)
resi
dual
(pp
m)
0 2 4 6 8 10 12 14 16 18 200
500
1000
1500
2000
bact
eria
(pp
m)
data
fit
0 2 4 6 8 10 12 14 16 18 20-100
-50
0
50
100
time (min)re
sidu
al (
ppm
)
0 2 4 6 8 10 12 14 16 18 200
500
1000
1500
2000
bact
eria
(pp
m)
data
fit
0 2 4 6 8 10 12 14 16 18 20-15
-10
-5
0
5
10
time (min)
resi
dual
(pp
m)
1st order fit
J = 7.9736x105
2nd order fit
J = 1.6776x104
3rd order fit
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.