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

Jac*_* Lu 11 arrays matlab 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 ]
Run Code Online (Sandbox Code Playgroud)

[ 3 6 0 5 ]应该获得矢量.

Jon*_*nas 10

这是一个较短的版本,结合了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
Run Code Online (Sandbox Code Playgroud)


Amr*_*mro 4

这是一个版本:

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
Run Code Online (Sandbox Code Playgroud)

编辑:考虑这个替代解决方案:

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

v =
     3     6     0     5
Run Code Online (Sandbox Code Playgroud)