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!