MATLAB: How to get n by n matrix from a given matrix

matlab functionmatrix

If suppose I want to input a matrix
A = [1,2,3;
4,5,6;
7,8,9]
I then choose a number, lets say '2'.
How would I get all possible two by two matrices from matrix A?
A = [1,2,3;
4,5,6;
7,8,9]
with the answer being;
[1,2; 4,5], [2,3; 5,6], [4,5; 7,8], [5,6; 8,9]
Thank you

Best Answer

If you have the image processing toolbox, you could use nlfilter for this. The downside is that it pads the matrix with 0s, so give extra submatrices that you have to remove. For n = 2, it's not harduous:
A = [1,2,3; 4,5,6; 7,8,9];
subAs = nlfilter(A, [2 2], @(block) {block}); %simply return each sliding block as a scalar cell array
subAs = subAs(1:end-1, 1:end-1);
celldisp(subAs)
For arbitrary n, it's a bit more complicated:
A = reshape(1:200, 10, 20)
nrows = 5;
ncols = 8;
subAs = nlfilter(A, [nrows, ncols], @(block) {block});
subAs = subAs(floor((nrows+1)/2):end-ceil((nrows-1)/2), floor((ncols+1)/2):end-ceil((ncols-1)/2));
celldisp(subAs)