Search code examples
rpseudocode

How to compute the grand sum of a matrix?


I have a matrix of size 4 x 10. I want to compute the sum all possible entries of the sum. In other words, if you have a 2 x 2 matrix

2 3
4 1

then there are 2^2 sums (2 + 3, 2 + 1) and (4 + 3, and 4 + 1). Similarly, if you have a 2 x 3 matrix, there would be 2^3 = 8 total sums. Duplicates are allowed. Since my matrix is a 4 x 10, this has 1,048,576 total sums.

How exactly do I compute this in R? Pseudocode is also fine since I am fairly sure I can translate into R. But specialized R packages/functions would be better.


Solution

  • What about this?

    m <- matrix(c(2,3,4,1), ncol = 2, byrow = T)
    apply(expand.grid(m[,2],m[,1]),1,sum)
    [1] 5 3 7 5