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

后端 未结 6 1537
误落风尘
误落风尘 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:24

    Usually I don't go with a for loop solution, but this is fairly intuitive:

    N = 3;
    [ii,jj] = find(A);
    B = zeros(size(A,1),N);
    for iRow = 1:size(A,1),
        nzcols = jj(ii==iRow);
        B(iRow,:) = A(iRow,nzcols(1:N));
    end
    

    Since you are guaranteed to have more than N nonzeros per row of A, that should get the job done.

提交回复
热议问题