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

后端 未结 4 2224
执念已碎
执念已碎 2021-02-20 03:22

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?

For example, for the matrix

         


        
4条回答
  •  离开以前
    2021-02-20 03:54

    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
    

提交回复
热议问题