Resize and sum a matrix
23 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam
2021-1-11
编辑:Adam
2021-1-11
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.
更多回答(2 个)
Walter Roberson
2021-1-11
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 个评论
Bruno Luong
2021-1-11
编辑:Bruno Luong
2021-1-11
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 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!