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<
N
N = 3<
Using accumarray with no loops:
accumarray
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