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.

Upvotes: 3

Views: 256

Answers (3)

rayryeng
rayryeng

Reputation: 104474

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);

Upvotes: 0

Divakar
Divakar

Reputation: 221514

You can use matrix-multiplication -

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

Upvotes: 6

Robert Seifert
Robert Seifert

Reputation: 25232

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

Upvotes: 8

Related Questions