# Print a java matrix

3

I'm trying to print a matrix diagonally, that is, the one in

``````1 2 3
4 5 6
7 8 9
``````

print 1 2 4 3 5 7 6 8 9

I have this, in which I only print up to 7 because if it does not leave the matrix:

``````public class matriz {
public static void main(String args[]) {

int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
imprimirMatriz(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
int x = 0;
int y = 0;
for (int i = 0; i < lado; i++) {
x = i;
y = 0;
while (x >= 0) {

System.out.print(matriz[y][x] + " ");
x--;
y++;

}
}
}
}
``````

Another problem I have is to print a part of the matrix, print the lower triangular of the same in reverse, where you have to print 9 8 7 5 4 1, print me 9 8 5 7 4 1, inserting two numbers of position. The code:

``````public class matrizmas {
public static void main(String args[]) {

int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
imprimirMatriz(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
for (int i = lado - 1; i >= 0; i--) {
for (int j = lado - 1; j >= i; j--) {
System.out.print(matriz[j][i]);

}

}
System.out.println();
System.out.println();

}
}
``````

asked by Fernando 24.01.2017 в 17:51
source

1

Well all the answers are good, I bring you a version that does the same thing that you want to get, using for control cycles, which in my opinion are used more to tour matrize.

``````public class Main {

public static void main(String[] args){
int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
//imprimimos la primer matriz
imprimirMatriz(matriz);
System.out.println();
//imprimimos la segunda
imprimirMatrizInversa(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
//Para este ciclo aremos que recorra una  fila de mas para poder recorrer todas
for (int i = 0; i <= 2 * (fila - 1); i++) {
for (int j = 0; j < columna; j++) {
//restamos la fila menos la columna
int x = i - j;
//aqui validamos si x es mayo o igual a cero y que x sea menor a la longitud de la matriz
//entonces imprimimos
if (x >= 0 && x < matriz.length) {
System.out.print(matriz[j][x]+" ");
}
}

}
}

public static void imprimirMatrizInversa(int[][] matriz) {
/**
* Para la matriz inversa o como gustes llamarle se empieza desde la ultima posicion menos 1
*/
for (int i = fila-1; i >=0; i--) {
/**
* Lo mismo aplica para recorrer las columnas empezamos de la ultima posicion menos 1
*/
for (int j = columna-1 ; j>=0 ;j--)
System.out.print(matriz[i][j]+" ");

//AHora bien para hacer el resultado que quieres despues de imprimir vamos restando una columna
//por fila recorrida
columna--;
}
}
}
``````

``````1 2 4 3 5 7 6 8 9
9 8 7 5 4 1
``````

1

You can do it this way too

``````public static void imprimirMatriz(int[][] matriz) {
int x = 0;
int y = 0;
int yAux = 0;
int yAnt = 0;
int i = 0;
int xAnt = -1;
yAux = (x != xAnt ? yAux : yAux + 1);
xAnt = x;
yAnt = (y == lado -1 ? yAnt + 1 : yAnt);
terminado = (yAnt > 0 ? true : false);
while (x >= 0 && y < lado) {
System.out.print(matriz[y][x] + " ");
x--;
y++;
}
i++;
}
}
``````

Regarding your second problem, this is solved

`````` public static void imprimirMatriz2(int[][] matriz) {
for (int i = lado - 1; i >= 0; i--) {
for (int j = i; j >= 0; j--) {
System.out.print(matriz[i][j]);
}

}
``````

1

You can do it like this

``````public class Matriz {
public static void main(String args[]) {

int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
imprimirMatriz(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
// limite es el indice maximo de un lado
int limite = matriz.length;
int x = 0;
int y = 0;
for (int i = 0; i < 2*limite-1 ; i++) {
// aquí discriminas si y cuanto i sobresale la dimensión de
// la matriz. en vez de aumentar x, la diferencia se agrega a y
x = (i<limite) ? i : limite-1;
y = (i<limite) ? 0 : i-limite+1;
// también tenemos que asegurarnos que el puntador
// no sobresale y
while (x >= 0 && y < limite) {

System.out.print(matriz[y][x] + " ");
x--;
y++;

}
}
}
}
``````

Console:

``````1 2 4 3 5 7 6 8 9
``````

the following code

``````x = (condicion) ? valor : otroValor;
``````

is a shorter way to write

``````if ( condicion ) {
x = valor;
} else {
x = otroValor;
}
``````

Alternatively you can do it as in the following example for matrices of other dimensions:

``````public class Matriz {
public static void main(String args[]) {

Matriz matriz=new Matriz(5);
matriz.imprimirMatriz();
}

private int [][] matriz;
private int dimension;

public Matriz(int dimension){
this.dimension = dimension;
matriz = new int[dimension][dimension];
generarMatriz();
}

private final void generarMatriz(){
for (int y = 0; y < dimension; y++){
for (int x = 0; x < dimension; x++){
matriz[x][y]=1+x+y*dimension;
System.out.print(String.format("%02d ",matriz[x][y]));
}
System.out.println();
}
}

private boolean outBounds(int x, int y){
return ( x<0 || x>=dimension || y<0 || y>=dimension );
}

private void imprimirDiagonal(int a, int b){
int x = a;
int y = b;
do{
System.out.print(String.format("%d ", matriz[x--][y++]));
}while(!outBounds( x, y ));
}

public void imprimirMatriz(){
for (int x = 0; x < dimension; x++ ) imprimirDiagonal( x, 0 );
for (int y = 1; y < dimension; y++ ) imprimirDiagonal( dimension-1, y );
}

}
``````

0

Following the example that @Mariano put in this other similar question and that I recommend you read, I propose this other more compact solution that takes advantage of a property that has the matrix in which the sum of the indexes of a diagonal give the same result.

The code for an array (n, m) for your `imprimirMatriz` method would be:

``````public static void imprimirMatriz(int[][] matriz) {
int m = matriz[0].length;
int n = matriz.length;
String salida = "";

for(int i = 0; i < n + m - 1; i++){
for (int x, y = Math.min(i,m - 1); y >= 0 && (x = i - y) < n; y--) {
salida += matriz[x][y] + " ";
}
}

System.out.println(salida.trim());
}
``````

Which gives the following output in your case:

1 2 4 3 5 7 6 8 9

If you add a column of zeros at the end and stop being square it also works and gives this result:

1 2 4 3 5 7 0 6 8 0 9 0

This way if you want to print only part of the matrix you can play with the values that `i` can take (instead of starting with 0 and ending with n + m-1 you can pass it only by n-1 to print a diagonal, etc ...)