Skip to content

Instantly share code, notes, and snippets.

@titandiaz
Last active May 3, 2018 05:04
Show Gist options
  • Save titandiaz/71a159a62d494e61bd0f753b7947f094 to your computer and use it in GitHub Desktop.
Save titandiaz/71a159a62d494e61bd0f753b7947f094 to your computer and use it in GitHub Desktop.
como hacer la traspuesta de una matriz en java
package traspuestaDeUnaMatriz;
public class traspuestaMatriz {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matriz = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
int[][] matrizT = new int[matriz[0].length][matriz.length];
int x, y;
for(x = 0; x < 4; x++)
{
for(y = 0; y < 3; y++)
{
System.out.print(matriz[x][y] + "\t");
}
System.out.println("");
}
System.out.println("");
for (x = 0; x < matriz.length; x++)
{
for (y = 0; y < matriz[x].length; y++)
{
matrizT[y][x] = matriz[x][y];
}
}
System.out.println("Matriz Traspuesta" + "\n");
for(x = 0; x < matriz[x].length; x++)
{
for(y = 0; y < matriz.length; y++)
{
System.out.print(matrizT[x][y] + "\t" );
}
System.out.println();
}
}
}
@cybergaala
Copy link

¿Por qué en el ultimo for anidado pones matriz[x].length; en el for externo?

for(x = 0; x < matriz[x].length; x++){
    for(y = 0; y < matriz.length; y++){
        System.out.print(matrizT[x][y] + "\t" );
    }
    System.out.println();
}

En mi caso al cambiar las dimensiones de la matriz a [3][3] me da error. Lo cual se soluciona agregando matriz[x].length; en el for interno.

for(x = 0; x < matriz.length; x++){
    for(y = 0; y <  matriz[x].length; y++){
        System.out.print(matrizT[x][y] + "\t" );
    }
    System.out.println();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment