Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transpose double[][] matrix with a java function?

Tags:

java

matrix

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.

like image 233
gurehbgui Avatar asked Mar 16 '13 13:03

gurehbgui


3 Answers

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);
}
like image 35
Santiago Ordax Avatar answered Nov 13 '22 13:11

Santiago Ordax


    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;
    }
like image 104
mystdeim Avatar answered Nov 13 '22 12:11

mystdeim


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()
like image 4
Wen-Bin Luo Avatar answered Nov 13 '22 13:11

Wen-Bin Luo