# Re: [R] sum of unknown number of matrices

From: John Fox <jfox_at_mcmaster.ca>
Date: Wed, 04 Jun 2008 11:20:48 -0400

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.

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. Received on Wed 04 Jun 2008 - 16:57:26 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 04 Jun 2008 - 18:30:41 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.