Removing zeros and then vertically smoothing the matrix

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

For instance,

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

How can I remove zeros and then vertically collapse the matrix so that it looks like this:

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

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

The matrix can be quite large (hundreds to hundreds in size). Thus, an effective method will be appreciated.

+4
source share
6 answers
  • ( , ):

    A_reduced_v = reshape(nonzeros(A), nnz(A(:,1)), []);
    
  • ( , ):

    A_reduced_h = reshape(nonzeros(A.'), nnz(A(1,:)), []).';
    
+4

№1

, A , (.. ) -

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

-

>> 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

№2

A , (.. ) - -

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

-

>> 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
+3

, , , :

>> B = A';
>> C = B(:);
>> reshape(C(~C==0), size(A) - [1, 0])'

ans =

     1     2
     3     4
     5     6
+2

Since your zeros are always in the main diagonal, you can do the following:

l = tril(A, -1);
u = triu(A,  1);
out = l(:, 1:end-1) + u(:, 2:end)
+1
source

I came up with almost the same solution as Mr. E, although with a different team change. This solution is more universal because it uses the number of rows in Ato create a finite matrix instead of counting the number of zeros or taking a fixed number of zeros.

B = A.';
B = B(:);
C = reshape(B(B~=0),[],size(A,1)).'
0
source

The right and very easy way to do what you want:

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

A =

 0     1     2
 3     0     4
 5     6     0

A = sort((A(find(A))))

A =

 1
 2
 3
 4
 5
 6

A = reshape(A, 2, 3)

A =

 1     3     5
 2     4     6
0
source

All Articles