MATLAB: Closest value in an array, and how to correctly look it up afterwards

closest value

I am new to the world of MATLAB and programming in general. Somehow I managed to write this code (thanks to this forum), and, although the values for c(l,j) and index(l,j) are correctly found, when I use search_x(l,j) to find the corresponding x value, the wrong answer is provided.
for j = 1:N
for l = 1:NN
[c(l,j) index(l,j)] = min(abs(x(:,j)-y(l)));
search_x(l,j) = x(index(l,j));
end
end
I apologize for my incompetence. Thank you.

Best Answer

It is not entirely clear to me what you are trying to do. My best guess is that, for each element y(l) , you want to find the element in x that is closest to y(l). If so, the following should do the trick:
c = zeros(size(y));
index = zeros(size(y));
for l = 1:NN
[c(l),index(l)] = min(abs(x(:)-y(l)));
end
search_x = x(index)