how to count numer of "1" in matrix

1 回表示 (過去 30 日間)
Lukasz Jarod
Lukasz Jarod 2015 年 1 月 11 日
コメント済み: Image Analyst 2015 年 1 月 11 日
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??

採用された回答

Star Strider
Star Strider 2015 年 1 月 11 日
The easiest way:
nr_ones = nnz(matrix);
  3 件のコメント
Star Strider
Star Strider 2015 年 1 月 11 日
@John — Thank you for clearly explaining the additional options, their strengths and constraints.
Image Analyst
Image Analyst 2015 年 1 月 11 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by