To find the index of the element in an array closest to some given value, you can use the following code:
main.m61 chars5 lines
In this code, A
is the array you want to search, and value
is the number you want to find the closest match to. The min
function returns the minimum value of the absolute differences between A
and value
, and the second output argument idx
is the index of that minimum value in the array A
. The first output argument ~
is used to discard the minimum value itself, which we don't actually need.
So in this example, idx
would be 2, since the element in A
closest to 4
is 3
, which is the second element in the array.
gistlibby LogSnag