compare two matrix and for the elements in common find the minimum difference between specif fields
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all,
I've two matrices A and B. In the 1st columns of both, there are non unique numbers representing the serial code, e.g. 01 and 02 in my case. Only in the row intervals in A and B having the same serial code, I would find the index of closest value in the 2nd column of B compared with the 2nd column in A. Then, I would to extract from the 3th column of B the value defined by the index and store it in A.
A = [01 105 6;
01 203 12;
02 99 6;
02 306 15]
B = [01 0 5;
01 100 25;
01 200 55;
01 300 75;
02 0 0;
02 100 20;
02 200 30;
02 300 40;
02 400 50]
The following doesn't work correctly...
out=A;
for k=1:size(A,1)
ii=ismember(B(:,1),A(k,1));
[~,idx]=min(abs(A(k,2)-B(ii,2)));
out(k,4)=B(idx,3);
end
out
As result, I would a matrix C as:
C = [01 105 6 25;
01 203 12 55;
02 99 6 20;
02 306 15 40]
Any suggestion to do this?
0 commentaires
Réponses (1)
the cyclist
le 15 Fév 2017
Modifié(e) : the cyclist
le 15 Fév 2017
Here is a pretty obfuscated solution:
[~,idx] = min(abs(1./((B(:,1)'==A(:,1))) .* (B(:,2)'-A(:,2))),[],2);
C = [A,B(idx,3)];
2 commentaires
the cyclist
le 16 Fév 2017
That syntax will work with more recent versions of MATLAB. Try this instead:
[~,idx] = min(abs(1./((bsxfun(@eq,B(:,1)',A(:,1)))) .* (B(:,2)'-A(:,2))),[],2);
C = [A,B(idx,3)];
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!