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()
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
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;
}
|
Testing the
EqnSolver
Class
|