Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Values closest to a number

Asked by cfjunior on 27 Apr 2013

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

cfjunior

Products

No products are associated with this question.

2 Answers

Answer by Wayne King on 27 Apr 2013
Edited by Wayne King on 27 Apr 2013
Accepted answer

It looks like you are looking for the closest numbers where one is below 7 and one is above. If that is the case.

    A = [2 3 5 6 9 10 23 45 100]';
    num = 7;
    closest_below = max(A(A<num));
    closest_above = min(A(A>num));

because otherwise, 5 is just as close to 7 as 9 is.

1 Comment

cfjunior on 27 Apr 2013

Yes, thats what I need!! Thanks a lot!!

Wayne King
Answer by 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.

0 Comments

the cyclist

Contact us