Clear Filters
Clear Filters

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

2 views (last 30 days)
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!

Accepted Answer

the cyclist
the cyclist on 26 Dec 2016
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.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!