find index of nearest value in array in matlab

To find the index of the element in an array closest to some given value, you can use the following code:

main.m
A = [1 3 5 7 9];
value = 4;

[~, idx] = min(abs(A - value));
61 chars
5 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