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!