### Highlights fromCount

1.75

1.8 | 8 ratings Rate this file 18 Downloads (last 30 days) File Size: 426 Bytes File ID: #3327

# Count

24 Apr 2003 (Updated 28 Apr 2003)

Counts the number elements in a specified vector that match a specified criteria.

File Information
Description

Count(A,B)

COUNT (A,B)

Counts the number of elements in A that match the criteria specified in B.

Example:

Data = [1 2 3 4 3 2 7 6 9 1 1 2 5 9 9];

Count(Data,'==9')

ans =

3

MATLAB release MATLAB 6.5 (R13)
Tags for This File
Everyone's Tags
Tags I've Applied
04 Mar 2013

I don't want to rate this function, but thanks for the submission. If nothing else it helped me discover the find method.

10 Nov 2011

length(find(Data==9))

10 Nov 2011
18 Oct 2011

For me histc(x,unique(x)) did what I wanted. This gives me the frequency of each value that occurs in the vector x.

23 Mar 2007

Thanks for help.t's very usefull.

18 Oct 2006

If last comments have not shown me how to count using sum or find your script would be very usefull.
Your script allowed me to find a good solution. Thanks to you and to the reviewers

08 Jun 2006

dude, just use size(find(index == i),1) to find the number of times i exists in index.

18 Feb 2006

Poor help and worse programming style. This file should be removed.

08 Sep 2005

Duplicates built-in FIND.

09 Jun 2004

Hi I found the lack of a COUNT command quite astonishing. The problem with the solutions offered here is that they 'deliver more than needed' (i.e. position of the element). On a CPU instruction level, this requires an unneeded write to RAM, where an CPU register increment would suffice for the purpose of COUNT. I made three tests with a vector of 64800 elements:

Option 1:
if 1== 1
tic
sum(listeNZ==8)
toc
end

1603 occurences of 8
elapsed time: 0.0051

Option 2:
if 1== 1
tic;
length(find(listeNZ==8))
toc
end

1603 occurences of 8
elapsed time: 0.0038 !!!!!!!! :o (about 30% less time needed)

just for fun:
Option 3:
if 1==1
sums=0;
tic;
for k=1:64800
if listeNZ(k)==8
sums=sums+1;
end
toc
end

1603 occurences of 8
elapsed time: 0.1401 !!!!!!!! :O (about 40 times slower than option 2)

In conclusion, the times needed are too small to worry about, but a COUNT command should really be included in the standard nevertheless... I am really astonished that the length(find()) combo is faster than the sum(), though...

28 Apr 2003

Yes, it is true this is not the most efficent function.

I wrote it before I realised there was a find function - (see the date in the help comments) I didn't bother to change it.

28 Apr 2003

could also use the 'find' command coupled with 'size' to do the same thing.
>> size(find(Data==9))

28 Apr 2003

The function contains too much computing overhead. It also includes an unnecessary EVAL statement. One will usually be better off using the built-in SUM function together with the power of logical indexing.

Example:

>> Data = [1 2 3 4 3 2 7 6 9 1 1 2 5 9 9];
>> sum(Data == 9)

ans =

3

HTH, Denis.