1

This is my code, it should work, but when i transpose and print matrix, it outputs the same matrix, not transposed. Some explanation? It should change the matrix, not make copy and transpose then return. public void transpose(){

    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++){
            Object tmp=matrix[i][j];
            matrix[i][j]=matrix[j][i];
            matrix[j][i]=tmp;
        }
}
Paul
  • 13
  • 3
  • 1
    Hint: try printing your matrix after every loop step. Start with small matrices; and use different values for each cell. – GhostCat May 11 '16 at 16:48

2 Answers2

0

You've got wrong indices in the inner loop.

    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            Object tmp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = tmp ;
    }
Dmytro Titov
  • 2,802
  • 6
  • 38
  • 60
0

Your code doesn't transpose your matrix since you are overwriting your originally matrix by matrix[i][j]=matrix[j][i];

Here is a way to tranpose a matrix in Java: transpose double[][] matrix with a java function

Community
  • 1
  • 1
RomCoo
  • 1,868
  • 2
  • 23
  • 36