[Math] Transpose a square matrix code

applicationsmatrices

I know it's not programming area , but I think it's more related to math.

I have the following function:

public void transpose()
    {
        for(int i = 0; i < mat_size; ++i) {
            for(int j = 0; j < i ; ++j) {
                double tmpJI = get(j, i);
                put(j, i, get(i, j));
                put(i, j, tmpJI);
            }
        }
    }

Or in plain english, suppose matrix size = matix's number rows = matrix's num cols.


from $i = 0 $ to $size$ do:

–> for $j = 0$ to $i$ do:

—–> replace $mat_{i,j}$ with $mat_{j,i}$

–> make $j$ bigger in 1

make $i$ bigger in 1.


For the following matrix:

$$\begin{matrix}
1 & 0 & 0 \\
5 & 1 & 0 \\
6 & 5 & 1 \\
\end{matrix}$$

the transpose output is:

$$\begin{matrix}
1 & 0 & 6 \\
5 & 1 & 0 \\
0 & 5 & 1 \\
\end{matrix}$$

when the correct transpose is:

$$\begin{matrix}
1 & 5 & 6 \\
0 & 1 & 5 \\
0 & 0 & 1 \\
\end{matrix}$$

What is my problem?

Best Answer

I've just implemented the code in Java (adding the necessary code to feed in the matrix you gave as an example, implement the get and put methods and print the results) and it works fine for me, so there must be a problem elsewhere in your code. I've put my code below. It's not textbook, but it proves the point: there's nothing wrong with your transpose method. Run it and God permitting, you'll see that.

// program which transposes a matrix M and prints M and its transpose

public class Matrix {

    double[][] M = new double[3][3];

    static int mat_size=3;

    public Matrix()
    {
        M[0][0]=1;
        M[0][1]=0;
        M[0][2]=0;
        M[1][0]=5;
        M[1][1]=1;
        M[1][2]=0;
        M[2][0]=6;
        M[2][1]=5;
        M[2][2]=1;

        System.out.println("M");

        printMatrix();

        transpose();

        System.out.println("M'");

        printMatrix();

    }

    public static void main(String[] args) {

        new Matrix();

    }

    public void transpose()
    {
        System.out.println();

        for(int i = 0; i < mat_size; ++i) {
            for(int j = 0; j < i ; ++j) {
                double tmpJI = get(j, i);
                put(j, i, get(i, j));
                put(i, j, tmpJI);
            }
        }
    }



    public void printMatrix()
    {

        System.out.println();

        for(int i = 0; i < mat_size; ++i) {
            for(int j = 0; j < mat_size ; ++j) {
                System.out.print((int)get(i,j)+" ");
            }
            System.out.println();
        }

    }

    private void put(int i, int j, double d) {

        M[i][j]=d;

    }

    private double get(int i, int j) 

        return M[i][j];

    }

}