MATLAB: How to assign values of each sub matrix from main matriix into another matrix

image processingmatrix manipulationsliding window

I have a matrix of size 256*384. If we divide it into 4*4 blocks there will be total of 6144 sub matrices(4*4 size). If we divide it into 2*2 blocks there will be total of 24576 sub matrices(2*2 size). I have to get the first value of each sub matrix( (1,1) value of each sub matrix) into single matrix, second value ( (1,2) value ) of each sub matrix into other single matrix and so on upto last value of each sub matrix( (2,2) value for 2*2 sub matrix and (4,4) value for 4*4 sub matrix ) into single matrix. Example: A=[5 4 1 2;9 5 7 3;1 3 8 5;6 0 4 1]; (4*4 size) Divided into 2*2 submatrices The output should be as follows: B(1)=[5 1;1 8] (All first values of each 2*2 submatrix into one matrix) B(2)=[4 2;3 5] (All second values of each 2*2 submatrix into one matrix) B(3)=[9 7;6 4] (All third values of each 2*2 submatrix into one matrix) B(4)=[5 3;0 1] (All fourth values of each 2*2 submatrix into one matrix) and so on upto last value of each submatrix for large matrix.

Best Answer

Assuming that the number of input matrix rows/columns are exact multiples of the number of submatrix rows/columns, then this does the job quite nicely:
A = [1,2,1,2;3,4,3,4;1,2,1,2;3,4,3,4] % input array
[Ar,Ac] = size(A);
Nr = 2; % submatrix rows


Nc = 2; % submatrix columns


Sr = Ar/Nr;
Sc = Ac/Nc;
C = cell(Sr,Sc); % preallocate output cell array
for Kr = 1:Sr
for Kc = 1:Sc
C{Kr,Kc} = A(Kr:Sr:end,Kc:Sc:end);
end
end
You can easily concatenate the cell array contents into one numeric array:
Z = cat(3,C{:})
There are probably ways of doing this using reshape and permute, but the loop is easier to understand and is likely reasonably efficient anyway. Tested on the matrix from the original question:
>> A = [1,2,1,2;3,4,3,4;1,2,1,2;3,4,3,4]
A =
1 2 1 2
3 4 3 4
1 2 1 2
3 4 3 4
>> Nr = 2; % submatrix rows
>> Nc = 2; % submatrix columns
...
>> C{:}
ans =
1 1
1 1
ans =
3 3
3 3
ans =
2 2
2 2
ans =
4 4
4 4
And a larger example:
>> A = [1,2,3,4,1,2,3,4;5,6,7,8,5,6,7,8];
>> A = [A;A;A;A]
A =
1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8
1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8
1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8
1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8
>> Nr = 4; % submatrix rows
>> Nc = 2; % submatrix columns
...
>> C{:}
ans =
1 1
1 1
1 1
1 1
ans =
5 5
5 5
5 5
5 5
ans =
2 2
2 2
2 2
2 2
ans =
6 6
6 6
6 6
6 6
ans =
3 3
3 3
3 3
3 3
ans =
7 7
7 7
7 7
7 7
ans =
4 4
4 4
4 4
4 4
ans =
8 8
8 8
8 8
8 8