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

后端 未结 4 2585
执念已碎
执念已碎 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:39

    One-line solution with bsxfun:

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

    Or use the two outputs of max:

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

提交回复
热议问题