How to compare and merge matrices with same numbers?

4 次查看(过去 30 天)
I have a question about a code. I have two matrices, A and B. I would like to compare these two matrices based on the values of the columns 2 and 3. for example:
A=[1 2 3 4
9 6 7 8
10 5 4 7]
and
B= [8 2 3 4
11 6 7 8
5 5 6 7]
It is noticed that rows have same values of 2nd and 3rd column.
After the comparison of these two matrices I would like to create a new matrix C which would include keep the same rows of A and Bmatrix and
and finally to merge them (I want to keep the rows of table A that have the same values as columns 2 and 3 of table B. Finally, I want to build a matrix which will have the rows of table A and the rows of B that have the same value in the 2nd and 3rd columns)
I mean C= [ 1 2 3 4
9 6 7 8
10 5 4 7
5 5 6 7 ]
I have tried
clc
clear
T1=readmatrix('file1.txt');
T2=readmatrix('file2.txt');
A=T1(:,2:3);
B=T2(:,2:3);
C=[A;B];
C(:,end) = [];
[~,~,jj] = unique(C,'rows','stable');
C([false; diff(jj) == 0],:) = [];
writematrix(C,'output.txt','delimiter','\t');
could you please help me?

回答(1 个)

Jan
Jan 2022-12-15
A =[ 1 2 3 4; ...
9 6 7 8; ...
10 5 4 7];
B = [ 8 2 3 4; ...
11 6 7 8; ...
5 5 6 7];
m = ismember(B(:, 2:3), A(:, 2:3), 'rows');
C = cat(1, A, B(~m, :))
C = 4×4
1 2 3 4 9 6 7 8 10 5 4 7 5 5 6 7
  8 个评论
Ivan Mich
Ivan Mich 2022-12-30
编辑:Ivan Mich 2022-12-30
Is there a way to show where each row came from in my final table (Table C)?
eg the first row is from file 1 (table A), the second row from file 2 (Table B) etc.?
Peter Perkins
Peter Perkins 2023-1-4
Sure. You know that the first height(t1) rows in the result came from t1, and the last sum(~tf) rows came from t2. Add a variable to the result that's something like [ones(height(t1),1); 2*ones(sum(~tf),1)].

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by