2009-09-03 38 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

相關問題