Reputation: 131
Here is a 10x10 array arr
.
This arr
has 100 elements. And it has distribution from -10 to 10 and there are 5 0-value.
I did this code because I wanted to know the number of 0.
count = 0;
for i = 1: 10
for j = 1: 10
if (arr (i, j) == 0)
count = count +1;
end
end
end
Logically, count
should be 5 in MATLAB's workspace. and i
and j
are 10.
However, when I run the code, count
is 0.
This code can not count the numbers.
How can I count the numbers?
Upvotes: 2
Views: 829
Reputation: 2059
correct me if I'm wrong but it sounds like you want the number of occurrences of the numbers in your vector, here's an alternative if that is the case:
arr=[1 2 2;3 3 3;5 0 0;0 0 0]; % example array where 1,2,3 occur 1x,2x,3x and 5=>1x, 0=>5x
[x(:,2),x(:,1)]=hist(arr(:),unique(arr(:)));
outputs sorted category as first column, occurrences as 2nd column:
x =
0 5
1 1
2 2
3 3
5 1
Upvotes: 1
Reputation: 30047
You can just use nnz
to get the number of non-zero elements in a logical array, so the number of elements in arr
with the value 0
is
count = nnz( arr == 0 );
Please read Why is 24.0000 not equal to 24.0000 in MATLAB? for information about comparisons of floating point numbers, you may need to do
tol = 1e-6; % some tolerance on your comparison
count = nnz( abs(arr) < tol ); % abs(arr - x) for values equal to x within +/-tol
Upvotes: 2