Matching matrices based on two columns

6 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by