-2

I need to extract a 3x3 matrix from an image and store it separately, and it should continue like this till the end of image. For example, my image is the following matrix:

p = [ 1 2 3 4 5 6 7 8 9; ...
      1 2 3 4 5 6 7 8 9; ...
      1 2 3 4 5 6 7 8 9; ...
      1 2 3 4 5 6 7 8 9; ...
      1 2 3 4 5 6 7 8 9; ...
      1 2 3 4 5 6 7 8 9 ]

The output should be like this:

p1 = [1 2 3; 1 2 3; 1 2 3]
p2 = [4 5 6; 4 5 6; 4 5 6]
p3 = [7 8 9; 7 8 9; 7 8 9]

and so on....

Can you please suggest me code or a built-in function for this?

plesiv
  • 6,935
  • 3
  • 26
  • 34
  • @ZoranPlesivčak MATLAB interprets matrix definitions just fine without ellipses. They are superfluous in this case. – Eitan T Jun 17 '13 at 16:09
  • @EitanT I didn't know that... Maybe you should revert my change. – plesiv Jun 17 '13 at 16:14
  • @ZoranPlesivčak It doesn't really matter. You can do it too, if you want. – Eitan T Jun 17 '13 at 16:18
  • 1
    -1: I don't agree with the initial upvote. *Can you please suggest me code or a built-in function* shows lack of research effort. In addtion: Why do you have to extract the matrix and generate additional matrices? Why is indexing and performing computations in-place not an option? – Schorsch Jun 17 '13 at 16:23
  • 2
    possible duplicate of [How to divide a matrix into equals parts?](http://stackoverflow.com/questions/1817174/), [divide the image into 3*3 blocks](http://stackoverflow.com/questions/9972684/), [Divide a matrix into submatrices in MATLAB](http://stackoverflow.com/questions/12554522/) and many more... – Eitan T Jun 17 '13 at 16:30

2 Answers2

1

Simplest way to extract submatrices:

p1 = img(1:3, 1:3);
p2 = img(4:6, 4:6);
p3 = img(7:9, 7:9);

Function for doing slicing.

function imgsl = img_slice( img, ry, rx )
    [ Y X ] = meshgrid(ry, rx);
    imgsl = reshape(img(sub2ind(size(img),Y(:),X(:))),[length(rx) length(ry)]).';

Use it as follows:

p1 = img_slice( p, 1:3, 1:3 );
p2 = img_slice( p, 4:6, 4:6 );
p3 = img_slice( p, 7:9, 7:9 );
plesiv
  • 6,935
  • 3
  • 26
  • 34
0

The image processing toolbox has a im2col function (link).

B = im2col(p, [3 3], 'distinct');

Then each column of B is a 3x3 block made into a vector, and you can use reshape(B(:, i), 3, 3) to recover the i-th 3x3 block. Note there are zeros padded to p.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Da Kuang
  • 852
  • 1
  • 8
  • 15