How to compare and merge matrices with same numbers?

조회 수: 3 (최근 30일)
Ivan Mich
Ivan Mich 2022년 12월 15일
댓글: Peter Perkins 2023년 1월 4일
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에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by