# How to find a subset matrix in the main matrix and build a new matrix

13 ビュー (過去 30 日間)
Moe 2014 年 9 月 5 日
コメント済み: Moe 2014 年 9 月 7 日
Hi everyone,
Suppose I have two matrices A and B. The matrix A is a subset of matrix B (it can be possible that some of arrays or rows of matrix A were missing in matrix B). There is an ID column in the matrix B that rows with a unique ID can be used in building of matrix C.
If there is a similar row of matrix A in the matrix B, then copy this row to the matrix C. In addition, if there is more than one similar unique ID in the matrix B, then copy those ones as well in the matrix C.
For example: second row in matrix A [3,6,8,7,5] is found in the tenth row in the matrix B. Also, there are more than on unique ID (4), then both tenth and eleventh row of matrix B is copied in the matrix C.
Input:
A = [2,4,5,6,7;3,6,8,7,5;2,3,9,8,1;1,8,2,9,2;3,4,5,8,6;7,8,6,5,4;7,9,5,1,2;6,5,2,1,1;4,9,2,3,4;1,8,7,2,6];
B = [1,4,8,9,7,1;2,3,9,8,1,1;8,7,5,1,3,2;6,6,2,9,7,2;1,2,3,1,4,3;3,4,5,8,2,3;2,5,6,9,7,3;1,3,6,7,2,3;4,9,8,7,6,3;3,6,8,7,5,4;1,2,8,3,7,4;7,9,5,1,2,5;1,5,9,7,2,6;6,5,7,1,2,6;1,8,2,9,2,6;7,8,9,1,3,7;1,3,5,4,8,7;1,6,9,7,1,7;4,5,9,7,2,8;1,2,3,6,9,8;7,8,9,9,1,9;4,7,2,3,1,9;5,6,8,9,7,9;6,8,2,4,1,10;1,8,7,2,6,10;2,3,5,9,7,11;7,5,6,9,3,11;6,5,2,1,1,11;2,3,6,7,8,12];
Output:
C = [3,6,8,7,5,4;1,2,8,3,7,4;1,4,8,9,7,1;2,3,9,8,1,1;1,5,9,7,2,6;6,5,7,1,2,6;1,8,2,9,2,6;7,9,5,1,2,5;2,3,5,9,7,11;7,5,6,9,3,11;6,5,2,1,1,11;6,8,2,4,1,10;1,8,7,2,6,10];
Thanks.

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

### 採用された回答

Guillaume 2014 年 9 月 5 日

I assume that the order of the rows in C don't matter:
[~,~, ib] = intersect(A, B(:, 1:5), 'rows'); %find rows of A in B
ids = B(ib, 6); %get the ID of those rows
C = B(ismember(B(:, 6), ids), :); %get rows whose ID match
##### 1 件のコメント表示非表示 なし
Moe 2014 年 9 月 7 日
Thanks Guillaume!

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

### Community Treasure Hunt

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

Start Hunting!

Translated by