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)];
  댓글 수: 2
gianluca
gianluca 2017년 2월 16일
편집: gianluca 2017년 2월 16일
Thanks but it give me an error:
Error using ==
Matrix dimensions must agree.
the cyclist
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by