count number of ones in binary matrix

Answers (5)

Stephen23
Stephen23 on 20 Jan 2018
Edited: Stephen23 on 21 Jan 2018
Simplest and most efficient answer:
nnz(A)
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.
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.
function y = one(x)
c=0;
for i=1:length(x)
if(x(i)==49)
c=c+1;
end
end
y=c;
end

1 Comment

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')

Sign in to comment.

Categories

Asked:

on 20 Jan 2018

Edited:

on 2 Feb 2020

Community Treasure Hunt

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

Start Hunting!