Given two arrays A and B, how to get B values which are the closest to A.

2 次查看(过去 30 天)
Suppose I have two arrays ordered in an ascending order, i.e.:
A = [1 5 7], B = [1 2 3 6 9 10]
I would like to create from B a new vector B', which contains only the closest values to A values (one for each).
I also need the indexes. So, in my example I would like to get:
B' = [1 6 9]. Idx = [1 4 5]
Note that the third value is 9. Indeed 6 is closer to 7 but it is already 'taken' since it is close to 4.
Any idea for a suitable code?
Note: my true arrays are much larger and contain real (not int) values
Thanks!

采纳的回答

the cyclist
the cyclist 2016-12-26
Here is a very straightforward way to get your values of B_prime and Idx.
A = [1 5 7];
B = [1 2 3 6 9 10];
NA = length(A);
B_prime = zeros(1,NA);
B_orig = B;
for n = 1:NA
[~, j] = min(abs(A(n)-B));
B_prime(n) = B(j);
B(j) = [];
end
[~,Idx] = ismember(B_prime,B_orig);
I expect this code will run into problems if the values in B are not unique (but I did not test that for you).
After admittedly very little thought, I could not think of any easy way to vectorize this, given your requirement of not replicating elements of B.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by