Last active
December 23, 2015 09:59
-
-
Save adonley/6617923 to your computer and use it in GitHub Desktop.
Small LU matrix factoring function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public LUMatriciesAndAnswer luFactor(double[][] matrix) { | |
// Initialize L and U matrices | |
double [][] L = new double[matrix.length][matrix.length], U = matrix; | |
boolean unstable = false; | |
double pivot = 0; | |
// Set the diagonal of L to 1 | |
for(int i = 0; i < matrix.length; i++) { | |
L[i][i] = 1; | |
} | |
for(int i = 0; i < matrix.length - 1 && !unstable; i++) { | |
pivot = U[i][i]; | |
// If the pivot is 0, then the factoring is unstable | |
if(pivot == 0) | |
unstable = true; | |
for(int j = i+1; j < matrix.length && !unstable; j++) { | |
// Populate the L matrix | |
L[j][i] = U[j][i]/U[i][i]; | |
for(int k = i; k < matrix.length; k++) { | |
if(k == i) | |
// Get rid of any small non-zero values arbitrarily | |
U[j][k] = 0; | |
else | |
U[j][k] = (-L[j][i])*U[i][k] + U[j][k]; | |
} | |
} | |
} | |
// Return the factored matrices | |
return new LUMatriciesAndAnswer(L,U); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment