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!