Matching matrices based on two columns

5 ビュー (過去 30 日間)
SChow
SChow 2021 年 7 月 14 日
編集済み: Simon Chan 2021 年 7 月 14 日
I have two matrices A and B, I am trying to match these by 2 columns of B and when they dont match instert Nan as fill value
A=
1 0.1 0.22 5 82 855
2 0.22 0.23 58 8 888
31 0.23 0.25 55 5 958
95 0.25 0.28 55 8 97
99 0.29 0.51 33 52 55
and B= (this contains some elements from column 2 and 3 of matrix A
0.01 0.02
0.1 0.22
0.22 0.23
0.23 0.25
0.25 0.28
0.28 0.29
0.29 0.51
I am trying to have a matrix as follows
NaN 0.01 0.02 NaN NaN NaN
1 0.1 0.22 5 82 855
2 0.22 0.23 58 8 888
31 0.23 0.25 55 5 958
95 0.25 0.28 55 8 97
NaN 0.28 0.29 NaN NaN NaN
99 0.29 0.51 33 52 55
  1 件のコメント
SChow
SChow 2021 年 7 月 14 日
編集済み: SChow 2021 年 7 月 14 日
I tried the following, the error says "The logical indices in position 1 contain a true value outside of the array bounds."
i=ismember(B,A(:,3:4));
A(i,:)

サインインしてコメントする。

採用された回答

Simon Chan
Simon Chan 2021 年 7 月 14 日
編集済み: Simon Chan 2021 年 7 月 14 日
col=size(A,2);
row=size(B,1);
C = nan(row,col);
[~,idx] = ismember(B,A(:,2:3),'rows');
idx2=find(idx~=0); % Index for Member
idx3=find(idx==0); % Index for Non-member
idx(idx==0)=[];
C(idx2,:)=A(idx,:);
C(idx3,2:3)=B(idx3,:)
C is the result.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by