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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by