views:

519

answers:

4

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
@Matt, I fixed your identity link.
Bob Cross
+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
+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
I would only loop the diagonal as `new double` already creates a zero-filled array... despite not being a *great* difference.
Carlos Heuberger
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