How to find a specific row in the matrix and extract it to the new matrix
12 views (last 30 days)
Show older comments
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]
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/147435/image.jpeg)
2 Comments
Accepted Answer
Andrei Bobrov
on 2 Mar 2015
Edited: Andrei Bobrov
on 2 Mar 2015
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,:))});
0 Comments
More Answers (2)
Guillaume
on 2 Mar 2015
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)
0 Comments
Star Strider
on 2 Mar 2015
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},:);
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!