;+
; NAME:
; round2array
;
;
; PURPOSE:
; round a value to its nearest value in an array
;
;
; INPUTS:
; array: SORTED!! array to round the number into (must be 1-d)
; number: the number(s) to round to the array
;
; KEYWORD PARAMETERS:
; FORCE: force the program to return an answer even if the input is
; not sorted
;
;
; OUTPUTS:
; the index of the closest array element
;
; RESTRICTIONS:
; not fully tested for nan values...
;
;
;
; EXAMPLE:
; IDL> print, round2array(findgen(10), [3.4, 3.0, 6.7, 6.3])
; 3 3 7 6
;
; MODIFICATION HISTORY:
;
; Mon Sep 8 15:39:23 2008, Brian Larsen
;
; had a problem at the end point, fixed, probably lost
; some speed however
;
; Tue Aug 26 18:42:58 2008, Brian Larsen
;
; another x10 speed improvement suggested by Paolo
; Grigis
; http://groups.google.com/group/comp.lang.idl-pvwave/browse_frm/thread/5848f460a7aab59b/1aae381879eb7ef9#1aae381879eb7ef9
;
; Mon Jan 7 10:46:02 2008, Brian Larsen
;
; totally rewritten using value_locate greatly
; simplified and sped up (factor of 11)
; Changed order of inputs to
; match that of value_locate (sorry)
;
; Tue Oct 16 14:51:20 2007, Brian Larsen
;
; written and tested
;
;-
FUNCTION round2array, array, number, FORCE = force
n_a = n_elements(array)
IF n_a EQ 0 THEN $
message, /ioerror, 'must input an array'
IF is_sorted(array) EQ 0 AND ~keyword_set(force) THEN $
message, 'Input array must be sorted'
vl = value_locate(array, number)
ind_max = where(vl EQ n_elements(array)-1, n_ind_max, comp = comp)
IF n_ind_max LT n_elements(number) THEN $
vl[comp] += ( (number-array[vl[comp]]) GT (array[vl[comp]+1]-number))
IF n_ind_max NE 0 THEN $
vl[ind_max] = n_elements(array)-1
IF total(vl LT 0) NE 0 THEN BEGIN
ind = where(vl LT 0, n_ind)
vl[ind] = 0
ENDIF
IF total(vl GT n_elements(array)-1) THEN BEGIN
ind = where(vl GT n_elements(array)-1, n_ind)
vl[ind] = n_elements(array-1)
ENDIF
return, vl
END