/* Invert the nxn matrix A by Gauss elimination and pivoting */ /* Using row swaps rather than permutation indices */ #define PROG_DATE "February 7, 1998" #define MYNAME "" #include #include #include /* Do an example for a 5x5 matrix */ #define NN 5 int nn=NN; /* The matrix AA is assumed to be stored as a */ /* one-dimensional array of length nn*nn */ /* with the rows of AA stored in sequence. */ /* Storing AA as a long vector makes it easier */ /* to work with matrices whose dimensions are */ /* only known at run time */ /* A sample matrix A and vector Y: */ double aa[NN*NN] = { 4, 0, 4, 3, 3, 1, 2, 3, 4, 5, -1, 2, -1, 2, -1, 3, 1, 4, 1, 6, 2, 7, 1, 8, 3 }; double ainv[NN*NN]; /* Save the original matrix here */ /* (The algorithm destroys the original copies.) */ double asave[NN*NN], acheck[NN*NN]; void showmat(double *vv, int mm, int nn); /* Put the solution procedure in its own subroutine. */ /* The function */ /* */ /* int mat_GaussPiv_inv(aa,ainv,nn); */ /* */ /* finds the inverse of the nxn matrix A. /* If A is invertible, the inverse matrix is put in ainv[]. /* The matrix A is overwritten */ /* */ /* The function returns */ /* 0 if the matrix A is invertible (and AX=Y is solved ) */ /* -1 if A is not invertible (and AX=Y is NOT solved) */ /* */ int mat_GaussPiv_inv(double *aa, double *ainv, int nn); void main(void) { int i,j,k; double csum; printf ("Find the inverse of the nxn matrix A\n" " by Gauss elimination and pivoting.\n"); printf ("Vs. %s - %s\n", PROG_DATE, MYNAME); /* Show the sample matrix and forcing vector */ printf ("The %dx%d matrix A (to 5 significant figures) is:\n", nn,nn); showmat(aa,nn,nn); /* Save a copy of aa[] since the solution process */ /* destroys aa[] */ for (i=0; i mpiv) { mpiv=z; imax=k; } /* If the best diagonal element is 0.0, */ /* then the matrix is singular, so return -1 */ if (mpiv==0.0) return -1; if (imax>i) { /* Found a better pivot, so permute the two rows */ /* Physically permute the two rows, since we need */ /* the rows of AINV in the proper order at the end */ for (j=0; j=0; ) { if (A(i,i)!=1.0) { double fac=A(i,i); for (j=0; j=0; ) { double fac=A(k,i); A(k,i)=0.0; /* Don't forget the augmented AINV columns: */ for (j2=0; j2