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

graphgraph theoryloopsmathematicsmatricesmatrix manipulationsubgraphssubmatrix reation

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.

Best Answer

ii = 4;
Bii = A(any(A == ii,2),:);