Values closest to a number
Show older comments
How do I find the two closest numbers from a number in a vector column? For example, suppose I have:
A = [2 3 5 6 9 10 23 45 100]';
If the number I'm seaching is 7, my requested answer would be 6 and 9.
1 Comment
bym
on 27 Apr 2013
why wouldn't it return 5 & 6? 5 is as close as 9
Accepted Answer
More Answers (1)
the cyclist
on 27 Apr 2013
There are many possible ways to do this. Here is one way.
A = [2 3 5 6 9 10 23 45 100]';
v = 7;
idx_hi = find(A>7,1,'first');
twoClosest = A([idx_hi-1,idx_hi])
I assumed that your A vector was sorted, that all values are unique, etc. You want to be careful if these conditions are not met.
Categories
Find more on Shifting and Sorting 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!