[R] sum of unknown number of matrices

John Fox jfox at mcmaster.ca
Wed Jun 4 17:20:48 CEST 2008


Dear Shubha,

This problem was coincidentally used as an illustration in the Help Desk
column in the current R News.

Actually, the brute-force method of using a loop to accumulate the sum works
quite well; a more elegant alternative, recently brought to my attention by
Kurt Hornik, uses the Reduce() function.

Here's an example:

> matrices <- vector(mode="list", length=10000)
> for (i in 1:10000)
+   matrices[[i]] <- matrix(rnorm(10000), 100, 100)
> 
> system.time({
+   S <- matrix(0, 100, 100)
+   for (i in 1:10000) S <- S + matrices[[i]]
+   })
   user  system elapsed 
   0.59    0.00    0.59 
>   
> system.time(S1 <- Reduce("+", matrices))
   user  system elapsed 
   0.60    0.00    0.59 
> 
> range(S1 - S)
[1] 0 0

I hope this helps,
 John

------------------------------
John Fox, Professor
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
web: socserv.mcmaster.ca/jfox

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On
> Behalf Of Shubha Vishwanath Karanth
> Sent: June-04-08 10:54 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] sum of unknown number of matrices
> 
> Hi R,
> 
> 
> 
> I have a list of matrices. I need to get the sum of all the matrices in
> the list.
> 
> 
> 
> Example:
> 
> a=b=c=d=matrix(1:4,2,2)
> 
> l=list(a,b,c,d)
> 
> 
> 
> 
> 
> I need:
> 
> > a+b+c+d
> 
>      [,1] [,2]
> 
> [1,]    4   12
> 
> [2,]    8   16
> 
> 
> 
> Something like do.call("+",l) is not working...why is this?
> 
> 
> 
> 
> 
> I may not be knowing the number of matrices in the list...
> 
> 
> 
> Thanks, Shubha
> 
> 
> 
> This e-mail may contain confidential and/or privileged i...{{dropped:13}}
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list