compare two matrix and for the elements in common find the minimum difference between specif fields

3 次查看(过去 30 天)
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?

回答(1 个)

the cyclist
the cyclist 2017-2-15
编辑:the cyclist 2017-2-15
Here is a pretty obfuscated solution:
[~,idx] = min(abs(1./((B(:,1)'==A(:,1))) .* (B(:,2)'-A(:,2))),[],2);
C = [A,B(idx,3)];

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by