矩阵元素的按块求和 [英] Blockwise sum of matrix elements

查看:79
本文介绍了矩阵元素的按块求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从这样的事情出发:

I want to go from something like this:

1> a = matrix(c(1,4,2,5,2,5,2,1,4,4,3,2,1,6,7,4),4)
1> a
     [,1] [,2] [,3] [,4]
[1,]    1    2    4    1
[2,]    4    5    4    6
[3,]    2    2    3    7
[4,]    5    1    2    4

对于这样的事情:

     [,1] [,2]
[1,]   12   15
[2,]   10   16

...不使用for循环,plyr或其他方式而无需循环.可能的?我正在尝试将地理纬度/经度数据集从5弧分钟缩小到半度,并且我已经有了ascii网格.我指定块大小的小功能会很棒.我已经有成百上千个这样的文件,因此不使用并行化/超级计算机就可以快速完成此工作的事情将受到赞赏.

...without using for-loops, plyr, or otherwise without looping. Possible? I'm trying to shrink a geographic lat/long dataset from 5 arc-minutes to half-degree, and I've got an ascii grid. A little function where I specify blocksize would be great. I've got hundreds of such files, so things that allow me to do it quickly without parallelization/supercomputers would be much appreciated.

推荐答案

您可以为此使用矩阵乘法.

You can use matrix multiplication for this.

# Computation matrix:

mat <- function(n, r) {
  suppressWarnings(matrix(c(rep(1, r), rep(0, n)), n, n/r))
}

平方矩阵示例,在a的每一侧使用矩阵及其转置:

Square-matrix example, uses a matrix and its transpose on each side of a:

# Reduce a 4x4 matrix by a factor of 2:

x <- mat(4, 2)
x
##      [,1] [,2]
## [1,]    1    0
## [2,]    1    0
## [3,]    0    1
## [4,]    0    1

t(x) %*% a %*% x
##      [,1] [,2]
## [1,]   12   15
## [2,]   10   16

非正方形示例:

b <- matrix(1:24, 4 ,6)
t(mat(4, 2)) %*% b %*% mat(6, 2)
##      [,1] [,2] [,3]
## [1,]   14   46   78
## [2,]   22   54   86

这篇关于矩阵元素的按块求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆