2

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?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
ddjfjfj djfiejdn
  • 131
  • 1
  • 12
  • 2
    If `count` is zero, your array doesn’t have any zero values in it, because your code is correct. Wolfie explained in his answer how to count “almost zeros”, which seems to have been useful to you. But I wanted to add that your code is correct to count the number of values identical to 0. – Cris Luengo Sep 01 '18 at 19:26

2 Answers2

2

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
Wolfie
  • 27,562
  • 7
  • 28
  • 55
1

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
user2305193
  • 2,079
  • 18
  • 39