Search code examples
arraysmatlabmatrixmultidimensional-arraysubmatrix

partition a matrix into matrix of blocks


I want to divide an image data into blocks, for example if I have X matrix of 4*4, I want the result to be a matrix M of 2*2*2*2 where M(1,1,:,:)=X(1:2,1:2) and M(1,2,:,:)=X(1:2,3:4) and etc.

I found a way to divide it into a cell array using mat2cell but cell arrays seem not very supported in matlab, I search and ask on SO just to do things that can be done easily with ordinary matrices(and I get answers suggesting not to use cell arrays at all).

I searched the net and SO thoroughly , there are many many results all of them either solve a particular problem(like finding a solution to an equation, which I don't want here) or end up at suggesting mat2cell.

The closest result I found though is using reshape, I tried reshape(X,[2 2 2 2]) and got C=2*2*2*2 matrix but C(1,1,:,:) seems to be the first row of X not the first block and I can't figure out what to do next.

Someone suggested permute(C,[1 2 3 4]) but I still don't get the result I want.

I'm still beginner to matlab so forgive me if my question is simple, also I don't want for-loops, I want vector code, so What to do next after reshape ?

Edit

I tried the answer of that duplicate question and still I don't get the result I want, I tried these:

A=ones(40,40);
A(1:10,1:10)=32*ones(10,10);
A(11:20,1:10)=zeros(10,10);    
T = permute(reshape(A, size(A, 1), 10, []), [2 1 3]);  
T = permute(reshape(T, 10, 10, [], size(T, 3)), [2 1 3 4]); 

T was 10*10*4*4, exactly the size I want(40*40 into a matrix of submatrices each of 4*4) but the values are wrong, T(1,1,:,:)~=A(1:4,1:4)

What Am I doing wrong here ?


Solution

  • For the initial case (4x4 into 2x2x2x2x2) use

    M= permute(reshape(X',[2,2,2,2]),[4,2,3,1]);
    

    For a general case where size(X) = a x b) and size(M) = c x d x e x f such that a*b = c*d*e*f, for any natural number n, use

    M= permute(reshape(X',[c,d,e,f]),[4,2,3,1]);