我有一个矩阵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
中非零行的下标,如上所述。
答案 0 :(得分:2)
这是一种方式:
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
答案 1 :(得分:1)
我认为这可以满足您的需求(每列获得非零行索引)。它与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.';
结果:
>> 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