Getting all submatrices

I have an N × M m matrix like:

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

I want to get all P × Q submatrices (P, Q odd) without using a for loop.

The result s must be a matrix P × Q × ((NP + 1) · (MQ + 1)).

eg. 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] 
+6
source share
1 answer

im2col can help you:

 m = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >> P = 3; Q = 3; >> columnized = im2col(m,[PQ],'sliding'); >> nMatrices = size(columnized,2); >> s = reshape(columnized, [PQ 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 option 'sliding' finds all overlapping submatrices and returns each as a column vector of a (P · Q) element in columnized . To turn them back into matrices, reshape this (P · Q) × ((NP + 1) · (MQ + 1)) matrix into P × Q × ((NP + 1) · (MQ + 1)) one.

+6
source

All Articles