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?

1
  • 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. Commented Sep 1, 2018 at 19:26

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. So what if I want to know the number of 1 or 2 instead of 0?
@ddjfjfj I included this information in my answer, you would do nnz( abs(arr-2) < tol ) for 2 within some tolerance tol.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.