Linear Algebra and the C Language/a03x
Install and compile this file in your working directory.
/* ------------------------------------ */
/* Save as: c00c.c */
/* ------------------------------------ */
#include "v_a.h"
/* ------------------------------------ */
/* ------------------------------------ */
#define RA R4
#define CA C4
/* ------------------------------------ */
#define FACTOR_E +1.E-0
/* ------------------------------------ */
int main(void)
{
double tA[RA*CA]={
/* x**3 x**2 x**1 x**0 */
-125, +25, -5, +1,
-8, +4, -2, +1,
+8, +4, +2, +1,
+27, +9, +3, +1,
};
double tb[RA*C1]={
/* y */
-3.00 ,
+0.00,
+3.00,
-2.00,
};
double **A = ca_A_mR(tA, i_mR(RA,CA));
double **b = ca_A_mR(tb, i_mR(RA,C1));
double **Pinv = i_mR(CA,RA);
double **Pinvb = i_mR(CA,C1);
clrscrn();
printf(" Fitting a linear Curve to Data:\n\n");
printf(" A:");
p_mR(A, S10,P2,C7);
printf(" b:");
p_mR(b, S10,P2,C7);
printf(" Pinv = V invS_T U_T ");
Pinv_Rn_mR(A,Pinv,FACTOR_E);
pE_mR(Pinv, S12,P4,C10);
stop();
clrscrn();
printf(" Pinv b ");
mul_mR(Pinv,b,Pinvb);
p_mR(Pinvb, S10,P4,C10);
printf("\n The coefficients a, b, c of the curve are: \n\n"
" y = %+.9f*x^3 %+.9f*x^2 %+.9f*x %+.9f\n\n"
,Pinvb[R1][C1],Pinvb[R2][C1],Pinvb[R3][C1],Pinvb[R4][C1]);
stop();
f_mR(b);
f_mR(A);
f_mR(Pinv);
f_mR(Pinvb);
return 0;
}
/* ------------------------------------ */
/* ------------------------------------ */
Presentation :
Let's calculate the coefficients of a polynomial.
y = ax**3 + bx**2 + cx + d
Which passes through these four points.
x[1], y[1]
x[2], y[2]
x[3], y[3]
x[4], y[4]
Using the points we obtain the matrix:
x**3 x**2 x**1 x**0 y
x[1]**3 x[1]**2 x[1]**1 x[1]**0 y[1]
x[2]**3 x[2]**2 x[2]**1 x[2]**0 y[2]
x[3]**3 x[3]**2 x[3]**1 x[3]**0 y[3]
x[4]**3 x[4]**2 x[4]**1 x[4]**0 y[4]
That we can write:
x**3 x**2 x 1 y
x[1]**3 x[1]**2 x[1] 1 y[1]
x[2]**3 x[2]**2 x[2] 1 y[2]
x[3]**3 x[3]**2 x[3] 1 y[3]
x[4]**3 x[4]**2 x[4] 1 y[4]
Let's use the Pinv_Rn_mR() function to solve
the system that will give us the coefficients a, b, c, d
Screen output example:
Fitting a linear Curve to Data :
A :
-125.00 +25.00 -5.00 +1.00
-8.00 +4.00 -2.00 +1.00
+8.00 +4.00 +2.00 +1.00
+27.00 +9.00 +3.00 +1.00
b :
-3.00
+0.00
+3.00
-2.00
Pinv = V * invS_T * U_T
-5.9524e-03 +1.6667e-02 -3.5714e-02 +2.5000e-02
+1.7857e-02 +1.0408e-15 -1.4286e-01 +1.2500e-01
+2.3810e-02 -3.1667e-01 +3.9286e-01 -1.0000e-01
-7.1429e-02 +5.0000e-01 +1.0714e+00 -5.0000e-01
Press return to continue.
Pinv * b
-0.1393
-0.7321
+1.3071
+4.4286
The coefficients a, b, c of the curve are :
y = -0.139285714*x^3 -0.732142857*x^2 +1.307142857*x +4.428571429
Press return to continue.
Copy and paste in Octave:
function y = f (x)
y = -0.139285714*x^3 -0.732142857*x^2 +1.307142857*x +4.428571429;
endfunction
f (-5)
f (-2)
f (+2)
f (+3)