Lecture 10
Lecture 10
Lecture 10
Curve fitting
0.6 0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
0.6 0.2
0.5 180 0
0.4
0.3
210 330
0.2 polar(theta,r) plots a circle
6 6
4 4
2 2
0 0 -2 0 2
0 5 10 15 20 10 10 10
10 10
10 10
5 5
10 10
0 0
10 10
-5 -5
10 10
0 5 10 15 20 10
-2 0
10
2
10
Bar charts
Bar graphs are useful for reporting
data. Horizontal
Vertical Bar
BarGraph
Graphofofx-data
x-data
8
x = [1,3,8,5,4,6];
76
bar(x); generates
6
5
barh(x); generates 4
3
3
a horizontal bar graph.
2
2
11
0
0 11 2 2 3 3 4 4 5 5 6 67 8
Pie charts
Pie charts are another useful way of
reporting data.
Pie Chart of x-data
pie(x); 4%
11%
(cyan section)
5/(1+3+8+5+4+6) 19%
(yellow section)
30% 15%
etc.
19%
Curve fitting
The simplest way to fit a set of 2D
data is a straight line.
Linear regression is a method of
fitting data with a straight line.
Linear regression minimizes the
squared distance between data
points and the equation modeling the
data points. This prevents positive
and negative errors from canceling.
Linear approximation by
hand
x = [0,1,2,3,4,5]
y = [15,10,9,6,2,0]
slope (y2-y1)/(x2-x1) = (0-15) / (5-0) =
-3
Crosses y axis at 15 (note the point
(0,15) in our data)
yhand = -3x + 15
sum_of_squares = sum((y - yhand).^2) = 5
polyfit function
The polyfit function takes (x, y) data,
and the degree n of a polynomial as
input. It returns the coefficients of the
polynomial of degree n that best fits
the data.
Using our data:
14 14
12 12
10 10
8 8
6 6
4 4
2 2
0 0
-2 -2
-2 0 2 4 6 -2 0 2 4 6
Polynomial regression
Polynomial regression is used to fit a set
of data with a polynomial.
The polyfit function can be used to find
the best fit polynomial of a specified
degree; the result is the coefficients.
Warning: Increasing the degree of the best fit
polynomial can create mathematical models
that may fit the data better, but care must be
taken in your interpretation of the result.
polyval function
polyfitreturns the coefficients of a
polynomial that best fits the data.
To evaluate the polynomial at any
value of x, use the polyval function.
polyval requires two inputs: the array
of coefficients and the array of x-
values at the locations the
polynomial is to be evaluated.
Example using polyval
Referring
to the data from this lecture
that we used from the polyfit example: