-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleastSquareFit.c
134 lines (106 loc) · 2.13 KB
/
leastSquareFit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
Question: Find the Quadratic polynomial that is the least square fit to the following data:
x | 0 | 1 | 2 | 3
----------------------
f(x)| 1 | 0 | 1 | 2
and f(x)=C1+C2*x+C3*x^2
//**i solved the problem using Gauss elimination process
solution
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
int main()
{
double x[4]={0,1,2,3},b[4][1]={1,0,1,2};
double a[4][3],at[3][4],A[3][3],B[3][1],mat[3][4];
for(int i=0;i<4;i++)
{
a[i][0]=1;
a[i][1]=x[i];
a[i][2]=x[i]*x[i];
//a[i][3]=x[i]*x[i]*x[i];
}
/** making transpose matrix **/
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
at[i][j]=a[j][i];
}
}
/* multilication of transpose matrix X matrix */
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
A[i][j]=0;
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(int k=0;k<4;k++)
{
A[i][j]+=(at[i][k]*a[k][j]);
}
}
}
/* updating B */
for(int i=0;i<3;i++)
{
for(int j=0;j<1;j++)
{
B[i][j]=0;
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<1;j++)
{
for(int k=0;k<4;k++)
{
B[i][j]+=(at[i][k]*b[k][j]);
}
}
}
/** using gauss elimination process to find the least square fitted values **/
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
mat[i][j]=A[i][j];
}
mat[i][3]=B[i][0];
}
/** upper triangular matrix **/
for(int j=0;j<3;j++)
{
for(int i=j+1;i<3;i++)
{
int m=mat[j][j];
int n=mat[i][j];
for(int k=0;k<=3;k++)
{
mat[i][k]=(m*mat[i][k])-(n*mat[j][k]);
}
}
}
/** back substitution **/
double ans[3];
ans[3-1]=(mat[3-1][3]/mat[3-1][3-1]);
for(int j=3-2;j>-1;j--)
{
double sum=0;
for(int i=j+1;i<3;i++)
{
sum+=(mat[j][i]*ans[i]);
//printf("sum %9.3lf\n",sum);
}
ans[j]=(mat[j][3]-sum)/(mat[j][j]);
}
/** answer **/
for(int i=0;i<3;i++)
{
printf("c%d = %9.3lf\n",i+1,ans[i]);
}
}