フィルターのクリア

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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by