find the nearest values
조회 수: 7 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
채택된 답변
Stephen23
2020년 1월 24일
편집: Stephen23
2020년 1월 24일
>> 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
>> 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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!