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?
0 个评论
回答(1 个)
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)];
2 个评论
the cyclist
2017-2-16
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)];
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!