简体   繁体   中英

Count non-zero elements in every row of matrix

I am using MATLAB. I have a 8x1000 matrix, and I want a program that will give me a 8x1 matrix, where each entry counts the number of non-zero entries in the corresponding row of the 8x1000 matrix.

You can sum up the non-zero elements in every row, by simply converting the data to logicals before.

%// example data
A = randi(10,8,1000)-1;

%// count sum up non-zeros in every row
result = sum(logical(A),2)

result =

   904
   897
   909
   895
   885
   901
   903
   873

你可以使用matrix-multiplication -

out = (A~=0)*ones(size(A,2),1)  %// A is the input matrix

A more esoteric version could use accumarray and bsxfun with nnz as the function to apply the values to for each column / group of the input matrix A . Not as efficient as using sum and matrix multiplication, but still a method to think about :):

B = bsxfun(@times, 1:size(A,1), ones(size(A,2),1)).';
out = accumarray(B(:), A(:), [], @nnz);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM