2013-03-16 55 views
4

不要任何人有,我可以轉用Java的基質中有如下形式的函數:轉置雙[] []矩陣與Java函數?

double[][] 

我有這樣的功能:某處

public static double[][] transposeMatrix(double [][] m){ 
    for (int i = 0; i < m.length; i++) { 
     for (int j = i+1; j < m[0].length; j++) { 
      double temp = m[i][j]; 
      m[i][j] = m[j][i]; 
      m[j][i] = temp; 
     } 
    } 

    return m; 
} 

但它是錯誤的。

+5

來實現使然後嘗試問 – Sach 2013-03-16 13:15:44

+0

'對(INT J = + 1; ...'=>'對(INT J = 0; ... )' - 你也不需要返回m,這個調用者已經有了一個參考。 – assylias 2013-03-16 13:21:58

+0

@Pshemo這個人似乎太快了一點,似乎... – assylias 2013-03-16 13:24:22

回答

17
public static double[][] transposeMatrix(double [][] m){ 
     double[][] temp = new double[m[0].length][m.length]; 
     for (int i = 0; i < m.length; i++) 
      for (int j = 0; j < m[0].length; j++) 
       temp[j][i] = m[i][j]; 
     return temp; 
    } 
+1

不應該檢查'm [0]'是否不會產生'IndexOutOfBoundsException'? – 2015-11-04 17:28:50

1

的Java類矩陣轉置: -

import java.util.Scanner; 

public class Transpose { 

    /** 
    * @param args 
    */ 

    static int col; 
    static int row; 
    static int[][] trans_arr = new int[col][row]; 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Scanner sc = new Scanner(System.in); 
     int m = sc.nextInt(); 
     col = m; 
     int n = sc.nextInt(); 
     row = n; 

     int[][] arr = new int[row][col]; 
     for (int i = 0; i < row; i++) { 
      for (int j = 0; j < col; j++) { 
       arr[i][j] = sc.nextInt(); 
       System.out.print(arr[i][j] + " "); 
      } 
      System.out.println(); 
     } 
     int[][] trans_arr = new int[col][row]; 
     for (int i = 0; i < row; i++) { 
      for (int j = 0; j < col; j++) { 
       trans_arr[j][i] = arr[i][j]; 
      } 
     } 
     for (int i = 0; i < col; i++) { 
      for (int j = 0; j < row; j++) { 
       System.out.print(trans_arr[i][j] + " "); 

      } 
      System.out.println(); 
     } 

    } 

} 
0

如果你想使用一個外部庫,Apache的百科全書數學提供了矩陣轉置的效用。請參閱official site

首先,您必須創建一個雙數組double[][] arr,正如您已經完成的那樣。然後,轉置2D矩陣可以這樣

MatrixUtils.createRealMatrix(arr).transpose().getData()