Skip to content
Advertisement

How to convert lower triangular matrix into a vector?

I want to convert my triangular matrix into a vector.

Let’s say I have 7×7 lower triangular matrix. Something like this:

0  0  0  0  0  0  1

0  0  0  0  0  2  3

0  0  0  0  4  5  6

0  0  0  7  8  9 10

0  0  11 12 13 14 15

0  16 17 18 19 20 21

22 23 24 25 26 27 28

And I need to convert this matrix into a vector ignoring zeros. So, the result should be:

[1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... 28]

I have already made a matrix by the following code:

int specMas[][] = new int[7][7];
        Random rand = new Random();
        int i, j;
        
        for(j = 6; j > -1; j--) {
            
            for(i = 6; i > 5-j; i--) {
            
            specMas[i][j] = rand.nextInt(-100, 101);
            
            
            }
        }
        
        for (i=0; i<7; i++) {
            for (j=0; j<7; j++)
                System.out.print(specMas[i][j]);
            System.out.println();
        }

But I don’t really get how to convert that into a vector. Can you please explain me how?

Advertisement

Answer

Just filter out the 0 values as below

        int k = 0;
        Integer[] array = new Integer[specMas.length * specMas.length];

        for (i = 0; i < specMas.length; i++) {
            for (j = 0; j < specMas[i].length; j++) {
                array[k++] = specMas[i][j];
            }
        }
        Integer[] result = Arrays.stream(array)
                .filter(o -> o != 0).collect(Collectors.toList()).toArray(Integer[]::new);

And the result array will be you desired answer, by the way the concept of transforming the rank 2 tensors to vector is quit useful, with this approach you can transfer the rank 4 tensors (supper-operators) to tensor rank 2 (matrix) then study their behaviour in the new vector space .

Validate final result as

        for (i = 0 ; i< result.length ; i++){
            System.out.print(result[i]);
        }

example

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement