Find the first N non-zero elements in each row of a matrix

后端 未结 6 1544
误落风尘
误落风尘 2020-12-21 08:02

I have a matrix in MATLAB with zeroes and I would like to get another matrix with the first N non-zero elements in each row. Let\'s say for example N = 3<

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 08:37

    Using accumarray with no loops:

    N = 3;
    [ii,jj] = find(A); [ii,inds]=sort(ii); jj = jj(inds);
    lininds = ii+size(A,1)*(jj-1);
    C = accumarray(ii,lininds,[],@(x) {A(x(1:N)')}); %' cell array output
    B = vertcat(C{:})
    B =
         2     6     7
         3     2     4
         1     3     4
         1     2     1
    

提交回复
热议问题