How to compare and merge matrices with same numbers?
3 次查看(过去 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?
0 个评论
回答(1 个)
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, :))
8 个评论
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 Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!