Is there a clean way to find the number of elements in a vector that are "near" a specified constant?
Afficher commentaires plus anciens
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!
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 31 Mar 2013
If you know the edges of the bins, which is seems like you do, then you can just use histc().
A = [50 101 49 102 102 100 51 100 50 101 102 102]
edges = 2.5 : 5 : 112.5;
counts = histc(A, edges)
3 commentaires
Will Forfang
le 31 Mar 2013
Modifié(e) : Will Forfang
le 31 Mar 2013
Image Analyst
le 31 Mar 2013
You can only accept one answer. If you know that you will have values around known values, like 50 or 100, then you can use Cedric's answer. My answer will work no matter if the common values are 50, 100, or anything else, like 14 or 123 or whatever. Even then you have to somehow bin the values, which is what a histogram does. What if your values are 1,2,3,4,5,6,...99,100,101,102? How wide is your tolerance for "close enough"? If you picked 1, you'd get 3 values around 50. If you picked 15, you'd get 30 values around 50.
Will Forfang
le 31 Mar 2013
Catégories
En savoir plus sur Graph and Network Algorithms dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!