count number of ones in binary matrix

14 ビュー (過去 30 日間)
Aneesha Govindu
Aneesha Govindu 2018 年 1 月 20 日
編集済み: Stephen23 2020 年 2 月 2 日
1 0 1
0 1
1 1 0
i need the output as : no of ones is 5

回答 (5 件)

Stephen23
Stephen23 2018 年 1 月 20 日
編集済み: Stephen23 2018 年 1 月 21 日
Simplest and most efficient answer:
nnz(A)

Birdman
Birdman 2018 年 1 月 20 日
A=[1 0 1;0 0 1;1 1 0];
cnt=sum(A(A==1))

James Tursa
James Tursa 2018 年 1 月 20 日
Assuming you mean the sum of all elements:
A = your matrix;
result = sum(A(:));
If you really mean just the edges or something else, let us know.

Image Analyst
Image Analyst 2018 年 1 月 20 日
Do you really only care about the outer perimeter? So if the center is a 1, you want to ignore that? If so:
mTemp = m; % Make copy
mTemp(2, 2) = 0; % Make center zero so we won't count it if it's a 1.
numZeros = nnz(mTemp); % Effectively, count 1's in outer perimeter only.

sumanth kumar
sumanth kumar 2020 年 2 月 2 日
function y = one(x)
c=0;
for i=1:length(x)
if(x(i)==49)
c=c+1;
end
end
y=c;
end
  1 件のコメント
Stephen23
Stephen23 2020 年 2 月 2 日
編集済み: Stephen23 2020 年 2 月 2 日
Although the function does not have any help or code comments, it appears that it was written to count the character '1' (which has a character value of 49) in a character vector, in which case the simple MATLAB equivalent would be:
y = nnz(x=='1')

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by