creating smaller matrix from a large matrix
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Manoj Kumar V
am 4 Okt. 2023
Bearbeitet: Adam Danz
am 4 Okt. 2023
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 Kommentare
Akzeptierte Antwort
Voss
am 4 Okt. 2023
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 Kommentar
Voss
am 4 Okt. 2023
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')
Weitere Antworten (2)
Adam Danz
am 4 Okt. 2023
Bearbeitet: Adam Danz
am 4 Okt. 2023
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 Kommentare
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!