Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix scale-out

Tags:

r

scale

matrix

Given a 100x100 matrix, we want to compute a 20x20 matrix, every cell of it represents the mean of a 5x5 square of the original matrix.

How to perform it? (If you have any better name for this operation please comment to rename question).

like image 496
Ali Avatar asked Jul 27 '26 09:07

Ali


1 Answers

Here are a couple of options.

The straightforward approach is to use aggregate() from the raster package:

m <- matrix(1:10000, ncol=100)

library(raster)
r <- raster(m)
as.matrix(aggregate(r, 5))

## aggregate() also supports non-square aggregation windows
as.matrix(aggregate(r, c(20, 50)))
#        [,1]   [,2]   [,3]   [,4]   [,5]
# [1,]  975.5 2975.5 4975.5 6975.5 8975.5
# [2,] 1025.5 3025.5 5025.5 7025.5 9025.5

For a more elegant or obfuscated approach (depending on your point of view) use a couple of matrix multiplications:

m <- matrix(1:10000, ncol=100)

mm <- suppressWarnings(matrix(rep(c(1, rep(0, 20)), each=5), ncol=20, nrow=100))
(t(mm) %*% m %*% mm)/25
like image 187
Josh O'Brien Avatar answered Jul 30 '26 03:07

Josh O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!