简体   繁体   English

找到给定矩阵的每一行中最后一个非零元素的索引?

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

For an arbitrary sized matrix x , how do I find the index of the last non-zero element in each row of a given matrix? 对于任意大小的矩阵x ,如何找到给定矩阵的每一行中最后一个非零元素的索引?

For example, for the matrix 例如,对于矩阵

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 ]

the vector [ 3 6 0 5 ] should be obtained. 应该获得向量[ 3 6 0 5 ]

Here's a shorter version, combining find and accumarray 这是一个较短的版本,结合了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

Here's one version: 这是一个版本:

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

EDIT : Consider this alternative solution: 编辑 :考虑这个替代解决方案:

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

v =
     3     6     0     5

One-line solution with bsxfun : 使用bsxfun的单行解决方案:

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

Or use the two outputs of max : 或者使用max的两个输出:

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

My answer's a bit twisted but it should work too 我的回答有点扭曲,但也应该有效

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