Blockwise sum of matrix elements

前端 未结 3 1732
悲哀的现实
悲哀的现实 2020-12-18 01:39

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,]          


        
3条回答
  •  无人及你
    2020-12-18 02:41

    I guess that might help you, but still it uses sapply which can be considered as loop-ish tool.

    a <- matrix(c(1,4,2,5,2,5,2,1,4,4,3,2,1,6,7,4),4)
    block.step <- 2
    res <- sapply(seq(1, nrow(a), by=block.step), function(x) 
        sapply(seq(1, nrow(a), by=block.step), function(y) 
            sum(a[x:(x+block.step-1), y:(y+block.step-1)])
        )
    )
    res
    

    Is it anyhow helpful ?

提交回复
热议问题