how to count numer of "1" in matrix

i have i matrix with 1/0 (binary img) and i want to count all "1" that are in that matrix. how can i do that??

 Accepted Answer

The easiest way:
nr_ones = nnz(matrix);

3 Comments

+1. Just to add some information that I know Star knows, but may be useful to the asker...
NNZ is actually the fastest, most efficient way to do that count in MATLAB. Although it can be done using various tests or sums. For example, one could do it as sum(double(A(:))). The double is in there in case your image is stored perhaps as uint8 numbers, so they would first need to be converted to doubles or some larger integer form to prevent overflow.
Another alternative is to do an explicit find or some form of test, and count the number of pixels found. The point is, any such computation will involve relatively more CPU time.
@John — Thank you for clearly explaining the additional options, their strengths and constraints.
But (recalling my assembly language from decades ago), wouldn't nnz() ultimately involve doing a sum internally? In fact when I test the sum() vs. nnz() I find that sum() is a lot faster, sometimes 10 times faster:
m = randi(2, 10000,1000)-1;
tic
sum(double(m(:)))
toc
tic
nnz(m)
toc
ans =
5002536
Elapsed time is 0.004765 seconds.
ans =
5002536
Elapsed time is 0.048686 seconds.
The only way I could get nnz to be sometimes faster was when I was using a small matrix, like 10-by-10.

Sign in to comment.

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!