[英]Find the lowest location within rows where there are non-zero elements for each column in a matrix in MATLAB
[英]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.