How to compare and merge matrices with same numbers?

3 visualizaciones (últimos 30 días)
Ivan Mich
Ivan Mich el 15 de Dic. de 2022
Comentada: Peter Perkins el 4 de En. de 2023
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?

Respuestas (1)

Jan
Jan el 15 de Dic. de 2022
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 comentarios
Ivan Mich
Ivan Mich el 30 de Dic. de 2022
Editada: Ivan Mich el 30 de Dic. de 2022
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 el 4 de En. de 2023
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)].

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by