find the nearest values

7 views (last 30 days)
Rima Habib
Rima Habib on 24 Jan 2020
Commented: Rima Habib on 24 Jan 2020
Hallo,
I have a matrix B (5000*2) and A(1*2)
now I need to find the nearest values in B to A
meaning the closest nearest value in the first column of B to the A(1,1), and the closest nearest value in the second column of B to A(1,2)
the 2 values must have the same index, meaning the closet values must be taken as a couple not every one from different indexes.
I tried some thing like :
dist2 = sum((A - B) .^ 2, 2);
closest = B(dist2 == min(dist2),:);
but it only gives me the closest value of the first column and not the both.
and when I search for the values, I could find a better fit but its really hard as I need to to this for many points not just this one.
Does any one have any suggestions?
Thanks ahead!

Accepted Answer

Stephen23
Stephen23 on 24 Jan 2020
Edited: Stephen23 on 24 Jan 2020
You were almost there, you just need to use the second output from min to make it easier:
>> A = rand(1,2)
A =
0.39011 0.53114
>> B = rand(500,2);
>> [D,X] = min(sum((A-B).^2,2));
>> B(X,:)
ans =
0.41172 0.53908
If A has multiple rows then you can use permute like this:
>> A = rand(3,2)
A =
0.26960 0.78802
0.47827 0.75230
0.34524 0.46480
>> B = rand(500,2);
>> [D,X] = min(sum((A-permute(B,[3,2,1])).^2,2),[],3);
>> B(X,:)
ans =
0.26950 0.77584
0.49448 0.76722
0.34736 0.48158
Note that both of these examples require the scalar dimension expansion supported by MATLAB R2016b or later, for earlier MATLAB versions you will need to replace the subtraction with bsxfun.
  1 Comment
Rima Habib
Rima Habib on 24 Jan 2020
Thanks alot Stephen Cobeldick :)

Sign in to comment.

More Answers (1)

SChow
SChow on 24 Jan 2020
Try the ismember function

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!