Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
JazzMusic
JazzMusic le 26 Déc 2016
Commenté : JazzMusic le 26 Déc 2016
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!

Réponse acceptée

the cyclist
the cyclist le 26 Déc 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.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by