Count nonzero elements in each row of the matrix

I am using MATLAB. I have a matrix 8x1000

and I need a program that will give me a matrix 8x1

where each entry counts the number of non-zero entries in the corresponding row of the matrix 8x1000

.

+3


source to share


3 answers


You can add non-null elements to each row by simply translating data into logical partitions earlier. sum

%// 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

      

+7


source


You can use matrix-multiplication

-



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

      

+5


source


A more esoteric version could use accumarray

and bsxfun

with nnz

as a function to apply values ​​for each column / group of the input matrix A

. Not as efficient as using sum

and multiplying a matrix, but still a way to think about :):

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

      

0


source







All Articles