// ----------------------------------------------------------------------- /* LU Decomposition * with partial implicit pivoting * partial means that the pivoting only happems by row * implicit means that the pivots are scaled by the maximum value in the row */ #include #include #include #define SWAP /* #define DEBUG */ /* #define SWAP_TEST */ // ----------------------------------------------------------------------- void LUsubstitute(float **A,int n,int *Rowswaps,float *b); int LUdecomp(float **A,int n,int *Rowswaps,int *val); void InvrsMatrix(float **A,int n); // ----------------------------------------------------------------------- /* LUdecomp * inputs: A matrix of coefficients * n - dimension of A * outputs: A matrix replaced with L and U diagonal matrices (diagonal values of L == 1) * Rowswaps - vector to keep track of row swaps * Val - indicator of odd/even number of rowswaps */ int LUdecomp(float **A,int n,int *rowswaps,int *val) { float epsilon,*rowscale, temp; float sum; float pvt; int ipvt; int i,j,k; /* #ifdef SWAP int itemp; #endif */ rowscale = (float *)malloc(sizeof(float)*n); epsilon = 0.00000000001; /* small value to avoid division by zero */ *val = 1; /* even/odd indicator (valence) */ /* initialize the rowswap vector to indicate no swaps */ for (i=0; i temp) temp = fabs(A[i][j]); if (temp == 0) return(-1); /* got a row of all zeros - can't deal with that */ rowscale[i] = 1/temp; /* later we need to divide by largest element */ } #ifdef DEBUG printf("\nlargest value in each row\n"); for (i=0; i= pvt) {ipvt = i; pvt = temp;} #endif } #ifdef SWAP #ifdef DEBUG printf("performing row swaps in LUdecom\n"); #endif /* if a better pivot value is found, interchange the rows */ if (j != ipvt) { for (k=0; k=0; i--) { sum = b[i]; for (j=i+1; j=0; i--) { sum = b[i]; for (j=i+1; j=0; i--) { m = rowswaps[i]; if (m != i) { sum = b[i]; b[i] = b[m]; b[m] = sum; } } #endif return; } // ----------------------------------------------------------------------- /* INVERSEMATRIXC * compute the inverse of a matrix * by repeated calls to the linear solver, one call for each column of an identity matrix */ void InvrsMatrix(float **A,int n) { int i,j; float **Ainverse; int *rowswap; float temp; int val; rowswap = (int *)malloc(sizeof(int)*n); Ainverse = (float **)malloc(sizeof(float *)*n); for (i=0; i