简体   繁体   中英

take from matrix non-zero rows per column

I have a matrix A . Suppose it is:

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

and I want to get the non-zero rows subscripts per column in a new matrix.
In my example that will be,

B = [ 1 3 4 6 7 0 0 0; 
      4 5 6 7 8 0 0 0; 
      1 2 3 5 6 7 8 0] 

In terms of just size, if A=(m,n) , B will be B=(n,m) (the transpose). In terms of content, B contains the subscripts of the non-zero rows in A as described above.

Here is one way:

mask = ~sort(~A);     %// destination of row indexes in output
[ii,~]=find(A);       %// get the row indexes
B = zeros(size(A));
B(mask) = ii; B=B.'   %'//write indexes to output and transpose

I think this does what you want (get the non-zero row indices per column). It's very similar to this other question :

[r c] = size(A);
M = bsxfun(@times, A~=0, 1:size(A,2)).'; %'// substitute values by indices
[~, rows] = sort(M~=0,'descend'); %//'' push zeros to the end
cols = repmat(1:r,c,1);
ind = sub2ind([c r],rows(:),cols(:));
B = repmat(NaN,c,r);
B(:) = M(ind).';
B = B.';

Result:

>> B

B =

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM