Amir Sagiv
Amir Sagiv

Reputation: 386

how do I find the closest value to a given number in an array?

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

Upvotes: 1

Views: 5178

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

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

Upvotes: 3

Nishant
Nishant

Reputation: 2619

I am assuming that all of r,z,y are row vectors;

According to the code you provided, it looks like you need the value in z whose index is same as the index of the value in r closest to scalar y. The following code does the same for a row vector y.

function output = some_fun(r,z,y)
    %// column i of temp is abs(r - y(i))
    temp = abs(repmat(abs(y),size(r,2),1) - repmat(r',1,size(y,2))) % // it is a size(r,2) x size(y,2) matrix
    %// each column i of min_ has min(abs(r - y(i))) as all its entries
    min_ = repmat(min(temp),size(r,2),1);  % // it is a size(r,2) x size(y,2) matrix
    %// each column i of ind1 has value of 1 corresponding to the index of closest element of r to y(i) and zero for others
    ind1 = temp == min;
    %// row_(i) is the row index of ind1 where the value is 1 for column i in ind1.
    [row_ col_] = find(ind1);
    %// thus row_(i) is the index of element of r closest to y(i)
    output = z(1,row_);
end

Upvotes: 1

Related Questions