Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing zeros and then vertically collapse the matrix

In MATLAB, say I have a set of square matrices, say A, with trace(A)=0 as follows:

For example,

A = [0 1 2; 3 0 4; 5 6 0] 

How can I remove the zeros and then vertically collapse the matrix to become as follow:

A_reduced = [1 2; 3 4; 5 6]

More generally, what if the zeroes can appear anywhere in the column (i.e., not necessarily at the long diagonal)? Assuming, of course, that the total number of zeros for all columns are the same.

The matrix can be quite big (hundreds x hundreds in dimension). So, an efficient way will be appreciated.

like image 899
Val K Avatar asked Dec 24 '22 22:12

Val K


2 Answers

Case #1

Assuming that A has equal number of zeros across all rows, you can compress it horizontally (i.e. per row) with this -

At = A' %//'# transpose input array
out = reshape(At(At~=0),size(A,2)-sum(A(1,:)==0),[]).' %//'# final output

Sample code run -

>> A
A =
     0     3     0     2
     3     0     0     1
     7     0     6     0
     1     0     6     0
     0    16     0     9
>> out
out =
     3     2
     3     1
     7     6
     1     6
    16     9

Case #2

If A has equal number of zeros across all columns, you can compress it vertically (i.e. per column) with something like this -

out = reshape(A(A~=0),size(A,1)-sum(A(:,1)==0),[])  %//'# final output

Sample code run -

>> A
A =
     0     3     7     1     0
     3     0     0     0    16
     0     0     6     6     0
     2     1     0     0     9
>> out
out =
     3     3     7     1    16
     2     1     6     6     9
like image 36
Divakar Avatar answered Dec 27 '22 10:12

Divakar


  • To compress the matrix vertically (assuming every column has the same number of zeros):

    A_reduced_v = reshape(nonzeros(A), nnz(A(:,1)), []);
    
  • To compress the matrix horizontally (assuming every row has the same number of zeros):

    A_reduced_h = reshape(nonzeros(A.'), nnz(A(1,:)), []).';
    
like image 164
Luis Mendo Avatar answered Dec 27 '22 10:12

Luis Mendo