Skip to content
Advertisement

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

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.

Advertisement

Answer

    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;
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement