how to calculate mean of submatrices in a large matrix and print out a new matrix
10 views (last 30 days)
Show older comments
Hi,
I have a matrix 4x4
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 2x2
M1 = [11 12
21 22]
M2 = [31 32
41 42]
...
The final result is a new matrix 2x2 containing the mean value computed from the submatrices
Thanks in advance.
0 Comments
Accepted Answer
Stephen23
on 15 Oct 2020
Edited: Stephen23
on 15 Oct 2020
>> 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).
2 Comments
Stephen23
on 17 Oct 2020
>> M = randi(9,1000,1000); % fake data
>> N = 10; % size of submatrix
>> S = size(M)/N;
>> A = mean(reshape(permute(reshape(M,N,S(1),N,S(2)),[2,4,1,3]),S(1),S(2),[]),3);
and checking:
>> size(A)
ans =
100 100
>> A(1,1)
ans = 4.2100
>> V = M(1:N,1:N); mean(V(:))
ans = 4.2100
More Answers (1)
David Hill
on 15 Oct 2020
m=[mean(M(1:2,1:2),'all'),mean(M(1:2,3:4),'all');mean(M(3:4,1:2),'all'),mean(M(3:4,3:4),'all')];
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!