Trying to extract the rows from a matrix where the values from the first two columns match the values from another matrix

1 回表示 (過去 30 日間)
Hi, I am trying to extract the rows from a matrix where the values from the first two columns of that matrix match the values from another matrix.
Basically, if the values in column 1 AND column 2 match the values for column 1 AND column 2 from another matrix, I want to extract the entire row. I want to do this for each row where the values match, essentially making a new matrix of the extracted rows.
Any help would be appreciated! Thanks.

採用された回答

Dyuman Joshi
Dyuman Joshi 2024 年 1 月 31 日
%Sample data for example
y1 = magic(5)
y1 = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
y2 = y1;
y2(randi(25,1,5)) = 0
y2 = 5×5
17 0 1 8 15 0 5 7 14 16 0 6 13 20 22 10 12 19 21 3 11 18 25 0 0
%Comparison
idx = all(y1(:,1:2)==y2(:,1:2), 2)
idx = 5×1 logical array
0 0 0 1 1
out = y1(idx, :)
out = 2×5
10 12 19 21 3 11 18 25 2 9
If you are working with floating point numbers, use a tolerance to compare instead of equality
tol = 1e-6;
idx = all(abs(y1(:,1:2)-y2(:,1:2))<tol,2)
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2024 年 1 月 31 日
In that case
%Sample data for example
y1 = magic(5)
y1 = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
y2 = [y1; randi(25, 2, 5)];
k = randi(numel(y2),1,14);
y2(k) = k*5
y2 = 7×5
17 24 75 8 15 10 5 80 14 16 4 50 13 20 22 10 55 19 125 3 11 18 95 2 9 21 22 100 15 170 15 70 14 140 175
%Comparison
[idx1,idx2] = ismember(y1(:,1:2),y2(:,1:2),'rows')
idx1 = 5×1 logical array
1 0 0 0 1
idx2 = 5×1
1 0 0 0 5
out1 = y1(idx1, :)
out1 = 2×5
17 24 1 8 15 11 18 25 2 9
out2 = y2(idx2(idx1),:)
out2 = 2×5
17 24 75 8 15 11 18 95 2 9
For floating point numbers use ismembertol.
Michael Bochert
Michael Bochert 2024 年 1 月 31 日
Worked perfectly. Thank you so much!!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by