Matrix Inversion


Although it doesn't happen often, there may be times when you will need to determine the inverse of a matrix on its own rather than in the context of solving a system of equations. An example would be if you were using an implicit solution technique to perform a certain analysis. The gaussian() and luDecomp() methods we developed previously could be modified to compute a matrix inverse. Since the gaussJordan() method already calculates the matrix inverse, we will use it to create our matrix inverter method.

The modification is quite simple. All we do is remove the b vector as an input parameter and remove any operations performed on the b vector inside the method. The Gauss-Jordan elimination technique is used to convert the A matrix into its inverse. Remember that when the original A matrix is pivoted the computed inverse matrix will have its columns in the wrong order. We can unscramble the inverse matrix by interchanging its columns in the opposite order that the rows of the original A matrix were swapped. The resulting method is called invertMatrix() and its code listing is shown next .

 public static void invertMatrix(double a[][]) {   int i,j,k,m;   double temp;   int numRows = a.length;   int numCols = a[0].length;   int index[][] = new int[numRows][2];   //  Perform an implicit partial pivoting of the   //  a[][] array. We will provide a dummy b  array   //  to the partialPivot() method.   partialPivot(a, new double[numRows], index);   //  Perform the elimination row by row. First dividing   //  the current row by a[i][i]   for(i=0; i<numRows; ++i) {     temp = a[i][i];     for(j=0; j<numCols; ++j) {       a[i][j] /= temp;     }     a[i][i] = 1.0/temp;     //  Reduce the other rows by subtracting a multiple     //  of the current row from them. Don't reduce the     //  current row. As each column of the a[][] matrix     //  is reduced its elements are replaced with the     //  inverse a[][] matrix.     for(k=0; k<numRows; ++k) {       if (k != i) {         temp = a[k][i];         for(j=0; j<numCols; ++j) {           a[k][j] -= temp*a[i][j];         }         a[k][i] = -temp*a[i][i];       }     }   }   //  Unscramble the inverse a[][] matrix.   //  The columns are swapped in the opposite order   //  that the rows were during the pivoting.   for(j=numCols-1; j>=0; j) {     k = index[j][0];     m = index[j][1];     if (k != m) {       for(i=0; i<numRows; ++i) {         temp = a[i][m];         a[i][m] = a[i][k];         a[i][k] = temp;       }     }   }   return; } 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net