繁体   English   中英

从矩阵每列获取非零行

[英]take from matrix non-zero rows per column

我有一个矩阵A 假设是:

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] 

我想在新矩阵中获取每列的非零行下标。
在我的示例中,

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] 

就大小而言,如果A=(m,n) ,则B将为B=(n,m) (转置)。 就内容而言,如上所述, B包含A非零行的下标。

这是一种方法:

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

我认为这可以满足您的要求(每列获取非零行索引)。 这与另一个问题非常相似:

[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.';

结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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