Extract a sub-matrix if the first or second column contains a specific number

1 view (last 30 days)
I have a large matrix A, I want to extract submatrices B1, B2.. etc that contains the same number of columns as in A but only rows for which the first or second columns of A contains a specific number. For instance for this A matrix;
A=[1 4 0 0.0576 0 250 250 250;
4 5 0.017 0.092 0.158 250 250 250;
5 6 0.039 0.17 0.358 150 150 150;
3 6 0 0.0586 0 300 300 300;
6 7 0.0119 0.1008 0.209 150 150 150;
7 8 0.0085 0.072 0.149 250 250 250;
8 2 0 0.0625 0 250 250 250;
8 9 0.032 0.161 0.306 250 250 250;
9 4 0.01 0.085 0.176 250 250 250
]
Extract B such that it contains rows for which column 1 and column 2 in A contain the number '4' B4 should look like this
B4=[1 4 0 0.0576 0 250 250 250;
4 5 0.017 0.092 0.158 250 250 250;
9 4 0.01 0.085 0.176 250 250 250;
]
I have very huge matrices, I am wondering if there is a super efficient way to do this.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 9 Jul 2017
Edited: Andrei Bobrov on 9 Jul 2017
ii = 4;
Bii = A(any(A == ii,2),:);
  7 Comments
Andrei Bobrov
Andrei Bobrov on 10 Jul 2017
[ii,jj] = find(squeeze(any(A(:,1:2) == reshape(0:9,1,1,[]),2))); % R2016b and later
B = accumarray(jj,ii,[],@(x){A(x,:)});

Sign in to comment.

More Answers (0)

Categories

Find more on Graph and Network Algorithms 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!