Binary search for closest value in an array

버전 1.0.0.0 (1.43 KB) 작성자: Benjamin Bernard
Returns closest value and corresponding index in an increasingly ordered array.
다운로드 수: 375
업데이트 날짜: 2012/8/27

라이선스 보기

Input values
============
arr : increasingly ordered array of values in R
val : scalar in R

Description
===========
Returns the value and index of 'arr' that is closest to 'val'. If several entries are equally close, the first one is returned.

Limitations
===========
Works fine up to machine error, e.g. [v, i] = closest_value([4.8, 5], 4.9) will return [5, 2], since in float representation 4.9 is strictly closer to 5 than to 4.8. See also http://en.wikipedia.org/wiki/Floating_point

Purpose
=======
Why upload another binary search? I found that many uploaded files are unnecessarily complicated and either don’t have a predetermined outcome (f.ex. the first one) if there are several choices or crash if the value to be searched for lies outside the boundaries of the array. Also, this code is thought to be instructional for people new to Matlab to build their own binary searches on. That’s why I kept it to the simplest case where the array needs to be increasingly ordered and the first of several values is returned. The code could be easily adapted for returning the last index instead, to allow for decreasingly ordered arrays, for fractional indices or for other well-ordered spaces. If you are looking for an implementation in C that allows for all these behaviour modifications, here is a very nice one: http://www.mathworks.com/matlabcentral/fileexchange/30484-fast-binary-search

인용 양식

Benjamin Bernard (2024). Binary search for closest value in an array (https://www.mathworks.com/matlabcentral/fileexchange/37915-binary-search-for-closest-value-in-an-array), MATLAB Central File Exchange. 검색됨 .

MATLAB 릴리스 호환 정보
개발 환경: R2011b
모든 릴리스와 호환
플랫폼 호환성
Windows macOS Linux
카테고리
Help CenterMATLAB Answers에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!
버전 게시됨 릴리스 정보
1.0.0.0