How to find the closest value of a given number in a table?

advertisements

The Situation is as follows:

I have to arrays, symbolizing a positive domain x, and another array whose a function of that domain z

Now, I want, for a given point y, to find the z value in the nearest location. For thatI wrote the following function:

R0 = @(y) z(find(abs( abs(y). -  r) == min(abs(abs(y). - r))))

(The use of abs is for negative values of y, since z is symmetric)

This works perfectally well, unless y is a vector. So, if I use the following code:

y = [-1:0.01:1];
R0(y);

I get the following error:

Error using  ==
Matrix dimensions must agree.

Trying to debug it, I came to see that the find statement returned a 1*0 matrix, hence nothing. This is although the value of y ACTUALLY EXSIST in the r array.

What I really want is to get a new vector, which assign the nearest value in z for each value of y.

Other, totally different solutions might be used, so I prefer understanding why this solution doesn't work and how can I make it work.

Thanks


Your question is not very clear. If I understand correctly, for each element of y you want to find the closest element in z.

y = [1 2 3 4 5]; %// example data
z = [0 2.5 6]; %// example data
d = abs(bsxfun(@minus, y(:).', z(:))); %'// compute distance for all pairs
[~, ind] = min(d); %// index of minimizer in z for each value of y
result = z(ind);

In this example,

result =
        0    2.5000    2.5000    2.5000    6.0000