How to find the index of the closest value to some number in 1D array ?
조회 수: 1,226 (최근 30일)
이전 댓글 표시
How to find the index in 1D array that has closest value to some number ?
val =-1.03
val1 = 1.04
x = -10:0.009:10
ind1 = find (A==val) % will work if the val is exact match
댓글 수: 2
Din N
2023년 3월 17일
This does give the closest value, but if you want the closest value to be smaller than your target value? For example if my target value is 7300, how can I specify here that I only want the index for the closest value that is smaller than 7300?
채택된 답변
per isakson
2015년 3월 27일
편집: per isakson
2019년 4월 2일
Hint:
>> [ d, ix ] = min( abs( x-val ) );
>> x(ix-1:ix+1)
ans =
-1.0360 -1.0270 -1.0180
ix is the "index in 1D array that has closest value to" val
"if the val is exact match" that's tricky with floating point numbers
댓글 수: 2
Peter Kövesdi
2019년 4월 2일
Take care: This routine fails with uint data types. Transform them to double first:
double(x);
or
double(val);
as needed.
추가 답변 (3개)
Peter Kövesdi
2019년 4월 1일
ind = interp1(x,1:length(x),val,'nearest');
also does it.
But a short comparison shows disadvantages in timing:
f1=@()interp1(x,1:length(x),val,'nearest');
f2=@()min( abs( x-val ) );
timeit(f1)>timeit(f2)
댓글 수: 1
Andoni Medina Murua
2022년 8월 18일
편집: Andoni Medina Murua
2022년 8월 18일
However
interp1(x,1:length(x),val,'nearest');
works in case val is an array, which doesn't happen with
min( abs( x-val ) );
Revant Adlakha
2021년 2월 26일
You could also use something like this, where f(x) is the function and x is the value of interest.
ind = find(min(abs(f(x) - x)) == abs(f(x) - x));
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!