creating smaller matrix from a large matrix
Show older comments
I want to create a 16*16 square matrix from 4*4 square matric based on a condition that 4*4 (i.e. 256) elements add together to form a new element for smaller matrix. Example is shown below.

2 Comments
Torsten
on 4 Oct 2023
If this is an IQ test, I didn't pass it...
Manoj Kumar V
on 4 Oct 2023
Accepted Answer
More Answers (2)
You mean
rng("default")
A = rand(16);
for i = 1:4
for j = 1:4
B = A((i-1)*4+1:i*4,(j-1)*4+1:j*4);
A_compressed(i,j) = sum(B(:));
end
end
A_compressed
?
Here are two more options. Neither are very readable but I knew there was a grouping solution and a vectorized solution and I was in the mood for a challenge.
Grouping solution
The variable group is a matrix the same size as A that groups the values of A into 4x4 sub-matrixes.
rng("default")
A = randi(10,16);
group = repelem(reshape(1:16,4,4)',4,4);
sumVec = groupsummary(A(:),group(:),'sum'); % alternative: =splitapply(@sum,A(:),group(:));
m = reshape(sumVec,4,4)'
Vectorized solution
This reshapes matrix A into a 4-dimensional array and then permutes the array so that sum can be applied acros the first two dimensions. Then the results are reshaped back into a matrix.
m = reshape(sum(permute(reshape(A',4,4,4,4),[1 3 2 4]),[1,2]),4,4)'
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!