2009-09-03 467 views
0

是否有一个实用程序可以在Java中创建指定大小的单位矩阵?如何在Java中创建任意大小的单位矩阵?

+0

这是不是有人要求大学功课? – Justin 2009-09-03 17:00:19

+0

它甚至被贴上了不要靠近我的标签...... – 2009-09-03 17:21:36

+0

@Justin,我试图把问题变成更有用,更少功课的东西。 – 2009-09-03 17:29:26

回答

6

尝试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); 
+2

它现在是'RealMatrix标识= MatrixUtils.createRealIdentityMatrix(维);'。 – 2015-05-23 20:58:14

+0

@BobCross请编辑链接,因为404错误。 – 2016-10-05 13:06:07

+0

@p_d完成。谢谢! – 2016-10-05 17:50:22

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; 
    } 
} 
+0

我只会循环对角线,因为'new double'已经创建了一个零填充的数组...尽管不是很大的差异。 – 2009-11-25 15:01:24

+0

@CarlosHeuberger ..好主意。 5年后,我更新了我的答案:) – James 2015-06-09 23:58:34

1

内存,有效的解决方案是创建一个类似如此:

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; 
    } 
} 
+0

虽然你并不需要构造函数和私有变量,但是你可以使getValue成为静态的。 – Theodor 2011-10-14 05:40:15