11

Do anybody have a function with which I can transpose a Matrix in Java which has the following form:

double[][]

I have function like this:

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

but its wrong somewhere.

Roman C
  • 49,761
  • 33
  • 66
  • 176
gurehbgui
  • 14,236
  • 32
  • 106
  • 178
  • 7
    Make a attempt then ask – Sachin Mar 16 '13 at 13:15
  • `for (int j = i+1; ...` => `for (int j = 0; ...)` - also you don't need to return m, the caller already has a reference to it. – assylias Mar 16 '13 at 13:21
  • @Pshemo This one got closed a little too fast it seems... – assylias Mar 16 '13 at 13:24
  • @assylias Yes, it was closed before OP posted his attempt. I voted to reopen it after that. – Pshemo Mar 16 '13 at 13:26
  • @gurehbgui What are you trying to do? If you are trying to change positions of elements in "square" matrix then your code works correctly. If you want to transpose non square matrix lets say {{1,2,3},{4,5,6}} into {{1,4},{2,5},{3,6}} you will have to create and return new array because you cant add/delete rows to already existing array. – Pshemo Mar 16 '13 at 13:39
  • Please refer to my solution using Apache library – Wen-Bin Luo Aug 19 '17 at 02:37

7 Answers7

29
    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;
    }
Rob Watts
  • 6,866
  • 3
  • 39
  • 58
mystdeim
  • 4,802
  • 11
  • 49
  • 77
  • 4
    Shouldn't you check that `m[0]` does not result in an `IndexOutOfBoundsException`? – Raffi Khatchadourian Nov 04 '15 at 17:28
  • This code works perfectly, if you don't mess up rows with columns. [m[0].length] represents the size of the row in a newly created matrix, and [m.length] the column. So transposed matrix is created oppositely to the intuition. First it takes the size of the "old" column and then the size of the "old" row: `double[][] temp = new double[columnSize][rowSize];` – JacobTheKnitter Apr 27 '22 at 12:39
4

If you would like to use an external library, Apache Commons Math provides the utility to transpose a matrix. Please refer to it official site.

First, you have to create a double array double[][] arr, as you have already done. Then, the transposed 2d matrix can be achieved like this

MatrixUtils.createRealMatrix(arr).transpose().getData()
Wen-Bin Luo
  • 147
  • 1
  • 15
2

Since Java 8, you can do this:

public static double[][] transposeMatrix(final double[][] matrix) {

    return IntStream.range(0, matrix[0].length)
        .mapToObj(i -> Stream.of(matrix).mapToDouble(row -> row[i]).toArray())
        .toArray(double[][]::new);
}
1

Java Class to Transpose a matrix :-

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();
        }

    }

}
Nikhil Kumar
  • 2,618
  • 3
  • 21
  • 24
1

Here is the method

public static double[][] transpose(double arr[][]){
    int m = arr.length;
    int n = arr[0].length;
    double ret[][] = new double[n][m];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            ret[j][i] = arr[i][j];
        }
    }

    return ret;
}
Z A Abbasi
  • 129
  • 1
  • 8
1

Here is a code to transpose a two dimensional matrix "In Place" (not using another data structure to save output) and hence is more memory efficient:

Same below algorithm can be used for int or char or string data types as well.

  public static double[][] transposeDoubleMatrix(double[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                double tmp = matrix[j][i];
                matrix[j][i] = matrix[i][j];
                matrix[i][j] = tmp;
            }
        }
        return matrix;
    }
Dean Jain
  • 1,959
  • 19
  • 15
-1

Here's a small change!

for (int j = i; j < m[0].length; j++)
  • 1
    Hi, I see that you are new contributor to the site, could you please explain so it is not just a line of code. Thanks! – kuskmen Sep 07 '18 at 20:54