Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all submatrices

I have got an N×M matrix m like:

 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16

I want to get all submatrices of size P×Q (P,Q are odd) w/o employing a for-loop.

The result s should be a P×Q×((N-P+1)·(M-Q+1)) matrix.

E.g. if P=Q=3:

s(:,:,1) = [1 2 3;  5  6  7;  9 10 11]
s(:,:,2) = [2 3 4;  6  7  8; 10 11 12]
s(:,:,3) = [5 6 7;  9 10 11; 13 14 15]
s(:,:,4) = [6 7 8; 10 11 12; 14 15 16]
like image 218
kay Avatar asked Dec 04 '12 21:12

kay


People also ask

How do you calculate submatrices?

The number of submatrices There are (n – k + 1) sequences of consecutive rows of length k, such as 1:k, 2:(k+1), and so forth. Similarly, there are (m – k + 1) sequences of consecutive columns of length k. So the following SAS/IML function counts the number of submatrices of order k.

What does submatrix mean?

(ˈsʌbˌmeɪtrɪks ) noun. a matrix formed from parts of a larger matrix.

What are leading submatrices?

The principal submatrices of a matrix are the matrix itself and those submatrices obtained from it by repeatedly striking out a row and the column of the same index. The leading principal sub matrices are Lhose obtained by striking out exactly one row and its cOlTesponding column.

How do you traverse a submatrix from a matrix?

To find the submatrices it does this: take for example a 1x5 submatrix, what the code does is to fix the first line of the matrix and move step by step (along all the columns of the matrix) the submatrix from the left edge of the matrix to the right edge of the matrix, then the code fixes the second row of the matrix ...


1 Answers

im2col can help you out here:

m =
     1     2     3     4
     5     6     7     8
     9    10    11    12
    13    14    15    16

>> P = 3; Q = 3;
>> columnized = im2col(m,[P Q],'sliding');
>> nMatrices = size(columnized,2);
>> s = reshape(columnized, [P Q nMatrices])

s(:,:,1) =
     1     2     3
     5     6     7
     9    10    11
s(:,:,2) =
     5     6     7
     9    10    11
    13    14    15
s(:,:,3) =
     2     3     4
     6     7     8
    10    11    12
s(:,:,4) =
     6     7     8
    10    11    12
    14    15    16

im2col with the 'sliding' option finds all the overlapping submatrices and returns each as a (P·Q)-element column vector in columnized. To turn these back into matrices, we reshape this (P·Q)×((N-P+1)·(M-Q+1)) matrix into a P×Q×((N-P+1)·(M-Q+1)) one.

like image 193
KQS Avatar answered Sep 28 '22 00:09

KQS