MATLAB: Is there a clean way to find the number of elements in a vector that are “near” a specified constant

MATLABvector

I have a vector that is periodically updating, and I need to know whenever an element appears exactly eight times in the vector. But due to measurement errors, the element may vary slightly from its true value.
For example:
A = [50 101 49 102 102 100 51 100 50 101 102 102]
In this vector, no values repeat eight times exactly, but there are eight values "near" 100. That's what I'm looking for.
Here is my current method of automating this search. It updates a count when it sees an element +-5 from another element. Is there a simpler/cleaner way to do this?
for i=1:length(A);
count = 1;
LB = A(i)-5;
UB = A(i)+5;
for j = i:length(A)
if A(j) < UB && A(j) > LB
count = count+1;
end
end
if count == 8;
found = A(i);
end
Thanks!

Best Answer

Yes, you can proceed as follows:
>> n = sum(abs(A-100) < 5)
n =
8