Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the grand sum of a matrix?

Tags:

r

pseudocode

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.

like image 905
masfenix Avatar asked Jan 08 '23 07:01

masfenix


2 Answers

A terse way to achieve this for a matrix with any number of columns would be with:

rowSums(expand.grid(as.data.frame(m)))

as.data.frame(m) converts your matrix to a data.frame, which means it can be directly passed to the expand.grid function, which will operate on each column. rowSums efficiently computes the row sums of the result, which will result in significant efficiency gains compared to using apply with function sum:

m <- matrix(1:40, nrow=4)
system.time(apply(expand.grid(m[,1],m[,2],m[,3],m[,4],m[,5],m[,6],m[,7],m[,8],m[,9],m[,10]),1,sum))
#    user  system elapsed 
#   4.866   0.108   4.971 
system.time(rowSums(expand.grid(as.data.frame(m))))
#    user  system elapsed 
#   0.141   0.030   0.171

Edit: As suggested by @Roland, this is not particularly memory efficient because it takes the full cross product of the columns before performing any additions. A harder to read but more memory efficient version would be:

Reduce(function(x, y) rowSums(expand.grid(x, y)), as.data.frame(m))
like image 166
josliber Avatar answered Jan 19 '23 07:01

josliber


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
like image 43
DatamineR Avatar answered Jan 19 '23 08:01

DatamineR