Values closest to a number

조회 수: 1 (최근 30일)
cfjunior
cfjunior 2013년 4월 27일
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
bym
bym 2013년 4월 27일
why wouldn't it return 5 & 6? 5 is as close as 9

댓글을 달려면 로그인하십시오.

채택된 답변

Wayne King
Wayne King 2013년 4월 27일
편집: Wayne King 2013년 4월 27일
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
cfjunior
cfjunior 2013년 4월 27일
Yes, thats what I need!! Thanks a lot!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

the cyclist
the cyclist 2013년 4월 27일
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.

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by