標籤:void [] string esc line desc 相等 des src
工作中用到了行列轉置,把這兩種情況的演算法記下來,以便後用
1.行列數相等的轉置
1 /** 2 * @description 矩陣轉置 3 * @author oldmonk 4 * @time 2017年8月18日 5 */ 6 public class test { 7 8 public static void main(String [] args) { 9 int data [][] = new int [] [] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } ;10 System.out.println("----------------轉置前------------------------") ;11 print1(data) ;12 reverse(data) ;13 System.out.println("----------------轉置後------------------------") ;14 print1(data) ;15 }16 17 // 將矩陣轉置18 public static void reverse(int temp [][]) {19 for (int i = 0; i < temp.length; i++) {20 for (int j = i; j < temp[i].length; j++) {21 int k = temp[i][j] ;22 temp[i][j] = temp[j][i] ;23 temp[j][i] = k ;24 }25 }26 }27 28 // 將矩陣輸出29 public static void print1(int temp [][]) {30 for (int i = 0; i < temp.length; i++) {31 for (int j = 0; j < temp[i].length; j++) {32 System.out.print(temp[i][j] + "\t") ;33 }34 System.out.println() ;35 }36 }37 }
測試結果:
2.任意數組轉置
1 /** 2 * @description 任意數組轉置 3 * @author oldmonk 4 * @time 2017年8月18日 5 */ 6 public class test2 { 7 8 public static void main(String [] args)// 測試 9 {10 double [][] TestMatrix = { { 1, 22, 34, 22 }, { 1, 11, 5, 21 }, { 7, 2, 13, 19 } } ;11 double [][] MatrixC = Transpose(TestMatrix, 3, 4) ;12 13 System.out.println("-------轉置前---------") ;14 myPrint(TestMatrix);15 System.out.println("-------轉置後---------") ;16 myPrint(MatrixC);17 }18 19 /**20 * @descript 任意二維數組轉置21 * @author xujingyang22 * @time 2017年8月17日23 */24 public static double [][] Transpose(double [][] Matrix, int Line, int List) {25 double [][] MatrixC = new double [List] [Line] ;26 for (int i = 0; i < Line; i++) {27 for (int j = 0; j < List; j++) {28 MatrixC[j][i] = Matrix[i][j] ;29 }30 }31 return MatrixC ;32 }33 34 // 將矩陣輸出35 public static void myPrint(double temp [][]) {36 for (int i = 0; i < temp.length; i++) {37 for (int j = 0; j < temp[i].length; j++) {38 System.out.print(temp[i][j] + "\t") ;39 }40 System.out.println() ;41 }42 }43 }
測試結果:
java 矩陣轉置演算法