How can I find all elements within a certain range of each other?
3 views (last 30 days)
Show older comments
Suppose I have a vector A = [1 4 7 10 2 8] (in reality it is much longer). I want to find the indices of the elements which are within specific range of another element. So let's say my range = 1, it needs to return ans = [1 0 1 0 1 1] as 1 & 2 fit and 7 & 8. How do I do this effectively? I'd rather not use for loops.
thanks!
2 Comments
Image Analyst
on 15 Sep 2014
In reality, how much longer is it? A million numbers? Ten million? If it's less than 10,000 or so I would not be afraid of a for loop because that would be only 100 million iterations of a double for loop, which can be done in less than a second.
Accepted Answer
Guillaume
on 15 Sep 2014
Interesting problem. How about:
[sortedA, indices] = sort(A);
inrange = find(diff(sortedA) <= range);
inrangeAidx = unique([indices(inrange) indices(inrange+1)]);
isinrange = zeros(size(A)); isinrange(inrangeAidx) = 1;
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!