creating smaller matrix from a large matrix
33 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2023-10-4
M = randi(10,16,16); % 16-by-16 matrix of integers between 1 and 10
disp(M);
siz = [4 4]; % size of smaller matrices to divide M into
args = arrayfun(@(n,s)n*ones(1,s/n),siz,size(M),'UniformOutput',false);
m = cellfun(@(b)sum(b,'all'),mat2cell(M,args{:}))
% check
m(1,1) == sum(M(1:4,1:4),'all')
m(2,1) == sum(M(5:8,1:4),'all')
m(3,4) == sum(M(9:12,13:16),'all')
1 个评论
Voss
2023-10-4
Or using some loops:
M = randi(10,16,16); % 16-by-16 matrix of integers between 1 and 10
disp(M)
siz = [4 4]; % size of smaller matrices to divide M into
n = size(M)./siz;
m = zeros(n);
for ii = 1:n(1)
for jj = 1:n(2)
m(ii,jj) = sum(M((ii-1)*siz(1)+(1:siz(1)),(jj-1)*siz(2)+(1:siz(2))),'all');
end
end
disp(m)
% check
m(1,1) == sum(M(1:4,1:4),'all')
m(2,1) == sum(M(5:8,1:4),'all')
m(3,4) == sum(M(9:12,13:16),'all')
更多回答(2 个)
Adam Danz
2023-10-4
编辑:Adam Danz
2023-10-4
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)'
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!