bhavs
bhavs

Reputation: 2291

Count the number of times a number is repeating in a vector

I have created a vector containing zeros and 1's using the following command in a for loop.

G(:,i)=rand(K,1)<rand;

Since this is part of a larger problem at a particular stage I need to count the number of 1's that are present in each column.

I have tried to find the count using a for loop which is very messy and takes too long. I found that histc can be used for this but I get an error

 histc(G(:,1),1)
 First input must be non-sparse numeric array.

Is there a better way to do this or am I missing something here ?

Upvotes: 1

Views: 1569

Answers (1)

gnovice
gnovice

Reputation: 125854

If you have a matrix G containing zeroes and ones, and you want to know how many ones are in each column, all you need is SUM:

nZeroes = sum(G);

This will give you a vector containing a total for each column in G.

Upvotes: 3

Related Questions