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]
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.
(ˈsʌbˌmeɪtrɪks ) noun. a matrix formed from parts of a larger matrix.
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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With