How to find a specific row in the matrix and extract it to the new matrix

조회 수: 33 (최근 30일)
Can anyone give me any suggestion how I can find the specific row (matrix= criteria) from main matrix (big matrix) and then extract to the some sub-matrices (A, B, C)
Z = [1 1 1 2
2 2 3 1
3 1 3 4
4 2 1 3
5 1 1 2
6 2 3 1
7 1 3 4
8 1 1 2
9 2 3 1
10 1 3 4
11 1 1 2
12 2 1 3
13 2 1 3
14 2 1 3
15 2 3 1
16 1 3 4
17 2 1 3
18 1 1 2
19 1 1 2
20 2 3 1
21 2 3 1
22 1 3 4
23 1 1 2
24 2 1 3
25 2 1 3
26 2 3 1
27 1 3 4]
M = [1 1 2
2 3 1
1 3 4]
  댓글 수: 2
Moe
Moe 2015년 3월 2일
편집: Moe 2015년 3월 2일
Criteria is the second matrix in the photo.
For example I need to find all of rows in the first matrix that according to the "A" criteria has [1 1 2]. Therefore, output should be same as third matrix:
[1 1 1 2
5 1 1 2
8 1 1 2
11 1 1 2
18 1 1 2
19 1 1 2
23 1 1 2]

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2015년 3월 2일
편집: Andrei Bobrov 2015년 3월 2일
Z = [1 1 1 2
2 2 3 1
3 1 3 4
4 2 1 3
5 1 1 2
6 2 3 1
7 1 3 4
8 1 1 2
9 2 3 1
10 1 3 4
11 1 1 2
12 2 1 3
13 2 1 3
14 2 1 3
15 2 3 1
16 1 3 4
17 2 1 3
18 1 1 2
19 1 1 2
20 2 3 1
21 2 3 1
22 1 3 4
23 1 1 2
24 2 1 3
25 2 1 3
26 2 3 1
27 1 3 4];
M = [1 1 2
2 3 1
1 3 4];
[l,i0] = ismember(Z(:,2:end),M,'rows');
zz = Z(l,:);
out = accumarray(i0(l),(1:nnz(i0))',[],@(x){sortrows(zz(x,:))});

추가 답변 (2개)

Guillaume
Guillaume 2015년 3월 2일
Use ismember with the 'rows' option:
ismatchrow = ismember(Z(:, 2:end), M(1, :), 'rows');
A = Z(ismatchrow, :)
Or to obtain a cell array with all the submatrices:
[~, matchrow] = ismember(Z(:, 2:end), M, 'rows');
matches = cell(1, max(matchrow));
for m = 1:max(matchrow)
matches{m} = Z(matchrow == m, :);
end
celldisp(matches)

Star Strider
Star Strider 2015년 3월 2일
This works:
[Zu, ia, ic] = unique(Z(:,2:4), 'rows');
[Lia,Locb] = ismember(M,Zu,'rows');
for k1 = 1:size(M,1)
R{k1} = find(Locb(k1) == ic);
end
A = Z(R{1},:);
B = Z(R{2},:);
C = Z(R{3},:);

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by