Find common rows between two matrices with different number of columns

1 回表示 (過去 30 日間)
Bassem Mokhtar
Bassem Mokhtar 2024 年 1 月 30 日
コメント済み: Dyuman Joshi 2024 年 1 月 30 日
I have two matrices A and B.
A = [1 2 3; 4 5 6; 7 8 9]
A = 3×3
1 2 3 4 5 6 7 8 9
B = [1 3 20 2; 1 2 3 55; 7 8 9 10; 88 2 1 5]
B = 4×4
1 3 20 2 1 2 3 55 7 8 9 10 88 2 1 5
and I need to extract the rows in B matrix with common elements in A matrix, row by row.
The result shall be like that:
common_rows = [1 3 20 2; 1 2 3 55; 7 8 9 10]
common_rows = 3×4
1 3 20 2 1 2 3 55 7 8 9 10
Thanks.

採用された回答

Dyuman Joshi
Dyuman Joshi 2024 年 1 月 30 日
A = [1 2 3; 4 5 6; 7 8 9];
B = [1 3 20 2; 1 2 3 55; 7 8 9 10; 88 2 1 5];
%Indices of rows in B
idx = 1:size(B,1);
for k=idx
%If elements in a row of B are not common with all elements of any row
%in A, remove that row index
if ~any(all(ismember(A, B(k,:)),2))
idx = setdiff(idx, k);
end
end
idx
idx = 1×3
1 2 3
C = B(idx, :)
C = 3×4
1 3 20 2 1 2 3 55 7 8 9 10
  2 件のコメント
Bassem Mokhtar
Bassem Mokhtar 2024 年 1 月 30 日
Many thanks. It works!
Dyuman Joshi
Dyuman Joshi 2024 年 1 月 30 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeComputational Geometry についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by