# Matching matrices based on two columns

3 views (last 30 days)
SChow on 14 Jul 2021
Edited: Simon Chan on 14 Jul 2021
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
SChow on 14 Jul 2021
Edited: SChow on 14 Jul 2021
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 on 14 Jul 2021
Edited: Simon Chan on 14 Jul 2021
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.