In MATLAB, you can use the min
function to find the index of the value in an array that is closest to a given value. Here's an example:
92 chars5 lines
In this example, A
is the array you want to search, target
is the value you want to find the nearest value to, abs(A - target)
calculates the absolute difference between A
and target
, min
finds the minimum absolute difference, idx
is the index of the value in A
with the minimum absolute difference, and nearest_value
is the value in A
with the minimum absolute difference.
In JavaScript, you can use a similar approach to find the nearest value in an array. Here's an example:
190 chars7 lines
In this example, A
is the array you want to search, target
is the value you want to find the nearest value to, reduce
applies a function to each element of A
to find the element with the minimum absolute difference, idx
is the element with the minimum absolute difference, and nearest_value
is the value in A
with the minimum absolute difference. Note that in JavaScript, the idx
variable stores the value of the nearest element, not the index of the nearest element.
gistlibby LogSnag