如何在Java中创建任意大小的单位矩阵?

com*_*eek 0 java math linear-algebra

是否有用于在Java中创建指定大小的标识矩阵的实用程序?

Bob*_*oss 6

尝试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)

  • 它现在是`RealMatrix identity = MatrixUtils.createRealIdentityMatrix(dimension);`. (3认同)

Jam*_*mes 5

如果您只想使用二维数组来表示矩阵而没有第三方库:

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)