尝试Apache Commons Math用于常用的线性代数:
// 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);
Run Code Online (Sandbox Code Playgroud)
如果您只想使用二维数组来表示矩阵而没有第三方库:
public class MatrixHelper {
public static double[][] getIdentity(int size) {
double[][] matrix = new double[size][size];
for(int i = 0; i < size; i++) matrix[i][i] = 1;
return matrix;
}
}
Run Code Online (Sandbox Code Playgroud)