Access the elements of a bidimensional matrix by column?

1

There is some way to get the columns of one matrix per column in two repetitive cycles, that is, if I have the matrix:

A =

[21.0][16.0][16.0][13.0][11.0]
[17.0][18.0][14.0][23.0][13.0]
[32.0][27.0][15.0][41.0][19.0]
[6.0] [10.0][12.0][15.0][43.0]

Access to the elements is done through two cycles, one for the rows and one for the columns, in code is:

for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A[i].length; j++) {
        System.out.print("["+A[i][j]+"]");
    }
    System.out.println();
}

Access is done for each row, but if you want to get something like:

Columna 0
[21.0]
[17.0]
[32.0]
[6.0] 
Columna 1
[16.0]
[18.0]
[27.0]
[10.0]
.
.
.
Columna N

I have not managed to do it.

Someone mentioned that it can be done by changing i by j when accessing the elements, something like this:

for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A[i].length; j++) {
        System.out.print("["+A[j][i]+"]");
    }
    System.out.println();
}

However, in doing so, throws an exception since j is greater than the total rows so the index is not found in the matrix.

How could I get the expected result?

    
asked by Juan Pinzón 08.09.2016 в 22:40
source

2 answers

1

Assuming that your two-dimensional array is N x N, the code would be like this:

double[][] A = ...
for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A.length; j++) {
        System.out.print(A[j][i] + " ");
    }
    System.out.println();
}

Assuming that your two-dimensional array is N x M where M is constant, the code would be like this:

double[][] A = ...
for (int i = 0; i < A[0].length; i++) {
    for (int j = 0; j < A.length; j++) {
        System.out.print(A[j][i] + " ");
    }
}
    
answered by 08.09.2016 / 23:55
source
1

This is my solution to the problem:

public class MatrizImprimirColumnas {

    public static void main(String[] args) {
        final int[][] M = {
                { 1, 2, 3, 4, 5, 6 },
                { 1, 3, 2, 5, 4, 6 },
                { 4, 6, 2, 5, 1, 3 }
        };

        imprimirMatrizPorColumnas(M);
    }

    private static void imprimirMatrizPorColumnas(int[][] m) {
        for (int i = 0; i < m[0].length; i++) {
            System.out.println("Columna " + (i + 1));
            imprimirColumna(m, i);
        }

    }

    private static void imprimirColumna(int[][] m, int col) {
        for (int i = 0; i < m.length; i++) {
            System.out.println("[" + m[i][col] + "]");
        }

    }
}

This is the output of the program:

Columna 1
[1]
[1]
[4]
Columna 2
[2]
[3]
[6]
Columna 3
[3]
[2]
[2]
Columna 4
[4]
[5]
[5]
Columna 5
[5]
[4]
[1]
Columna 6
[6]
[6]
[3]
    
answered by 09.09.2016 в 01:11