Is there a clean way to find the number of elements in a vector that are "near" a specified constant?
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Cedric
2013-3-31
编辑:Cedric
2013-3-31
Yes, you can proceed as follows:
>> n = sum(abs(A-100) < 5)
n =
8
4 个评论
Image Analyst
2013-3-31
Correct. I was trying to say, though not explaining it very well, that even if you use histc(), depending on where your edges are you could have different numbers in the bins. For example if you had 4 numbers just barely to the low side of 100 and another 4 just barely to the high side of 100, and the bin edge was chosen exactly at 100 then you'd have two bins with 4 counts, not one bin with 8 counts. So some thoughtful analysis of the numbers might need to take place before the counting (histogramming) takes place. I haven't put enough thought into it to come up with something that was truly super robust.
更多回答(1 个)
Image Analyst
2013-3-31
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 个评论
Image Analyst
2013-3-31
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!