Resize and sum a matrix
24 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I wasn't sure how to phrase my question, so apologies if it has been asked elsewhere and I couldn't find it!
What I want to do is re-size a Matrix, summing the values within adjacent elements together as it is re-sized. To give an example, let's say I start with a 4x4 Matrix:
array1 =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Then I want to re-size this into a 2x2 Matrix, summing adjacent values together such that the result is:
array2 =
14 22
46 54
Where 1 + 2 + 5 + 6 = 14, ...11 + 12 + 15 + 16 = 54 etc.
The above is just an example, the numbers would normally be random. I would always be wanting to reduce the Matrix dimensions by an integer number, e.g. 500x500 to 100x100, 40x40 to 20x20 etc.
Is there a built in function, or a simple way to do this?
Thanks in advance
0 commentaires
Réponse acceptée
Adam
le 11 Jan 2021
Modifié(e) : Adam
le 11 Jan 2021
If you have the Image Processing Toolbox you can use blockproc something like the following:
array2 = blockproc( array1, [n n], @(b) sum( b.data(:) ) )
where n is the size of block that you want to sum together (2 in this case or e.g. 5 in the case of 500x500 to 100x100).
This assumes, as you stated, that it is always an integer division of the dimensions.
Plus de réponses (2)
Walter Roberson
le 11 Jan 2021
N = 3;
array1 = randi(9, 12, 9)
S = conv2(array1, ones(N,N), 'same')
d = floor((N+1)/2)
S(d:N:end,d:N:end)
N2 = 4;
array2 = randi(9, 12, 16)
S2 = conv2(array2, ones(N2,N2), 'same')
d2 = floor((N2+1)/2)
S2(d2:N2:end,d2:N2:end)
0 commentaires
Bruno Luong
le 11 Jan 2021
Modifié(e) : Bruno Luong
le 11 Jan 2021
If you isist on "resize"
array1 =[1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16];
[m,n] = size(array1);
array2 = sum(permute(reshape(array1,[2 m/2 2 n/2]),[2 4 1 3]),[3 4])
0 commentaires
Voir également
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!