CE206 Curvefitting Interpolation 4
CE206 Curvefitting Interpolation 4
CE206 Curvefitting Interpolation 4
Interpolation
- Ex: density of water at different
temp.
Least-squares Regression
- Purpose is trend analysis or
hypothesis testing
v, m/s 10 20 30 40 50 60 70 80
F, N 25 70 380 550 610 1220 830 1450
1500
Is the relationship
1000
-linear? Which order?
(Linear or polynomial
F (N)
regression)
500
-nonlinear?
0
(Nonlinear regression)
0 20 40 60 80
v (m/s)
n xi yi xi yi
a1
n x x
2
2
i i
a0 y a1 x
St Sr i 1
r
2
St n
S r yi a0 a1 xi
2
i 1
(CE 205 lecture slides of details)
CE 206: Engg. Computation sessional Dr. Tanvir Ahmed
A MATLAB code for linear regression
function [a, r2] = linregr(x,y)
% input:
% x = independent variable
% y = dependent variable
% output:
% a = vector of slope, a(1), and intercept, a(2)
% r2 = coefficient of determination
n = length(x);
if length(y)~=n, error('x and y must be same length'); end
x = x(:); y = y(:); % convert to column vectors
sx = sum(x); sy = sum(y);
sx2 = sum(x.*x); sxy = sum(x.*y); sy2 = sum(y.*y);
a(1) = (n*sxy-sx*sy)/(n*sx2-sx^2);
a(2) = sy/n-a(1)*sx/n;
r2 = ((n*sxy-sx*sy)/sqrt(n*sx2-sx^2)/sqrt(n*sy2-sy^2))^2;
% create plot of data and best fit line
xp = linspace(min(x),max(x),2);
yp = a(1)*xp+a(2);
plot(x,y,'o',xp,yp)
grid on
CE 206: Engg. Computation sessional Dr. Tanvir Ahmed
Fitting a straight line
1600
>> [a, r2] = linregr(v,F)
1400
a =
1200
19.4702 -234.2857
1000
r2 =
0.8805 800
600
200
3.5
0
-200
10 20 30 40 50 60 70 80
3
2.5
Log-transformed data
>> [a, r2] =
2 linregr(log10(v),log10(F))
a =
1.5 1.9842 -0.5620
r2 =
1
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
0.9481
i1 i1
We can solve for the coefficients {a} using matrix
manipulations
>>F=F(:);
>>Z*F
ans =
5135
>>a=(Z*Z)\(Z*F)
312850 a =
20516500 -178.4821
16.1220
0.0372
Problems in transformation:
-Not all equations can be transformed easily or at all
-The best fit line represents the best fit for the transformed
variables, not the original variables.
Methodology:
-Write down the basis function.
-use MATLABs fminsearch function to find the
values of the coefficients where a minimum occurs
2.5384 1.4359
CE 206: Engg. Computation sessional Dr. Tanvir Ahmed
Comparison between regressions
F 0.2741v1.9842 transformed
F a1v a2
F 2.5384v1.4359 untransformed
2000
1500
untransformed
F (N)
1000
500
transformed
0
0 20 40 60 80
v (m/s)
CE 206: Engg. Computation sessional Dr. Tanvir Ahmed
Polynomial interpolation
(1) Use MATLABs polyfit and polyval function
- the number of data points should be equal to the number of coefficients
x = linspace(-1, 1, 9);
y = 1./(1+25*x.^2);
xx = linspace(-1, 1);
yy = spline(x, y, xx);
yr = 1./(1+25*xx.^2)
plot(x, y, o, xx, yy, -, xx, yr, --)
140
120
100
>> tt=linspace(0,110); 80
>> v1=interp1(t,v,tt);
>> plot(t,v,'o',tt,v1) 60
40
20
0
0 20 40 60 80 100 120