簡體   English   中英

找到給定矩陣的每一行中最后一個非零元素的索引?

[英]Find the index of the last non-zero element in each row of a given matrix?

對於任意大小的矩陣x ,如何找到給定矩陣的每一行中最后一個非零元素的索引?

例如,對於矩陣

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

應該獲得向量[ 3 6 0 5 ]

這是一個較短的版本,結合了findaccumarray

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ];
%# get the row and column indices for x
[rowIdx,colIdx] = find(x);
%# with accumarray take the maximum column index for every row
v = accumarray(rowIdx,colIdx,[],@max)'
v =
     3   6   0   5

這是一個版本:

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ];
c = arrayfun(@(k) find(x(k,:)~=0,1,'last'), 1:size(x,1), 'UniformOutput',false);
c( cellfun(@isempty,c) ) = {0};
v = cell2mat(c);

v =
     3     6     0     5

編輯 :考慮這個替代解決方案:

[m,v] = max( cumsum(x'~=0) );
v(m==0) = 0;

v =
     3     6     0     5

使用bsxfun的單行解決方案:

result = max(bsxfun(@times, x~=0, 1:size(x,2)).');

或者使用max的兩個輸出:

[val, result] = max(fliplr(x~=0).',[],1); %'
result = (size(A,2)+1-result).*val;

我的回答有點扭曲,但也應該有效

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ];
[~,pos] = max([fliplr(x~=0),ones(size(x,1))],[],2);
v = size(x,2)-pos' +1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM