MATLAB: How to calculate mean of submatrices in a large matrix and print out a new matrix

meansubmatrix

Hi,
I have a matrix 4×4
M =[
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44]
I want to calculate the mean of submatrix 2×2
M1 = [11 12
21 22]
M2 = [31 32
41 42]
The final result is a new matrix 2×2 containing the mean value computed from the submatrices
Thanks in advance.

Best Answer

>> M = [11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44;51,52,53,54;61,62,63,64]
M =
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
51 52 53 54
61 62 63 64
Using convolution is simple and relatively efficient:
>> A = conv2(M,ones(2,2),'valid')/4;
>> A = A(1:2:end,1:2:end)
A =
16.500 18.500
36.500 38.500
56.500 58.500
Or you could rearrange the matrix before calling mean:
>> S = size(M)/2;
>> A = mean(reshape(permute(reshape(M,2,S(1),2,S(2)),[2,4,1,3]),S(1),S(2),[]),3)
A =
16.500 18.500
36.500 38.500
56.500 58.500
Or split the matrix into submatrices:
>> A = cellfun(@(m)mean(m(:)),mat2cell(M,[2,2,2],[2,2]))
A =
16.500 18.500
36.500 38.500
56.500 58.500
Or use blockproc (requires the image toolbox).