import java.util.Arrays; public class TransposeMatrix { public static void main() { double [][] a = { {1, 8, -3}, {4, -2, 5} }; double[][] b; b = matrixTranspose(a); System.out.println( Arrays.toString(a[0]) ); System.out.println( Arrays.toString(a[1]) ); System.out.println( "Transpose:" ); System.out.println( Arrays.toString(b[0]) ); System.out.println( Arrays.toString(b[1]) ); System.out.println( Arrays.toString(b[2]) ); } public static double[][] matrixTranspose(double[][] m) { double[][] result = new double[m[0].length][m.length]; // result matrix has: // # rows = # columns in m (= m[0].length) // # columns = # rows in m (= m.length) for (int i = 0; i < m.length; i++) for (int j = 0; j < m[0].length; j++) result[j][i] = m[i][j]; // Copy m's element in row i and column j // to row j and column i in result return result; } }