Is there a utility to create an identity matrix of specified size in Java?
+4
A:
I recommend Jama for all your matrix needs. There's a call to generate an identity matrix (see the identity method).
Matt
2009-09-03 16:57:14
@Matt, I fixed your identity link.
Bob Cross
2009-09-03 17:33:43
+4
A:
Try Apache Commons Math for commonly used linear algebra:
// Set dimension to the size of the square matrix that you would like
// Example, this will make a 3x3 matrix with ones on the diagonal and
// zeros elsewhere.
int dimension = 3;
RealMatrix identity = RealMatrix.createRealIdentityMatrix(dimension);
Bob Cross
2009-09-03 17:26:00
+4
A:
If you just want to use a 2 dimensional array to represent the matrix and no 3rd party libraries:
public class MatrixHelper {
public static double[][] getIdentity(int size) {
double[][] matrix = new double[size][size];
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
matrix[i][j] = (i == j) ? 1 : 0;
return matrix;
}
}
James
2009-09-03 18:12:15
I would only loop the diagonal as `new double` already creates a zero-filled array... despite not being a *great* difference.
Carlos Heuberger
2009-11-25 15:01:24
A:
A memory-efficient solution would be to create a class like so:
public class IdentityMatrix{
private int dimension;
public IdentityMatrix(int dimension){
this.dimension=dimension
}
public double getValue(int row,int column){
return row == column ? 1 : 0;
}
}
Scott Fines
2009-11-25 14:40:52