find the nearest values

7 ビュー (過去 30 日間)
Rima Habib
Rima Habib 2020 年 1 月 24 日
コメント済み: Rima Habib 2020 年 1 月 24 日
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!

採用された回答

Stephen23
Stephen23 2020 年 1 月 24 日
編集済み: Stephen23 2020 年 1 月 24 日
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 件のコメント
Rima Habib
Rima Habib 2020 年 1 月 24 日
Thanks alot Stephen Cobeldick :)

サインインしてコメントする。

その他の回答 (1 件)

SChow
SChow 2020 年 1 月 24 日
Try the ismember function

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by