Re: [R] applying a function over a matrix 2N x M to produce a matrix N x M

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Fri, 22 Apr 2011 15:29:36 -0400

On Apr 22, 2011, at 2:38 PM, Richard M. Heiberger wrote:

> I like David's answer and it can be made much faster.
> I show three refinements, each faster than the preceding one.
>
> Rich
>
> > system.time(for (i in 1:1000)
> + mat[seq(1, nrow(mat), by=2), ]+mat[seq(2, nrow(mat), by=2), ]
> + )
> user system elapsed
> 0.18 0.00 0.19
> >
> > system.time(for (i in 1:1000)
> + mat[seqn <- seq(1, nrow(mat), by=2), ]+mat[seqn+1, ]
> + )
> user system elapsed
> 0.08 0.00 0.08

Yawn. Who cares about doubling speed?

> >
> > system.time(for (i in 1:1000)
> + mat[seqn <- seq(1, length=nrow(mat)/2, by=2), ]+mat[seqn+1, ]
> + )
> user system elapsed
> 0.05 0.00 0.05
> >
> > system.time(for (i in 1:1000)
> + {mat2 <- mat; dim(mat2) <- c(2,3,6); mat2[1,,]+mat2[2,,]}
> + )

Strong work, Richard. I like this answer much better than mine and I think it is truly novel. It does what I had thought should be possible, but I abandoned that effort and now see my brain was only working in two dimensions. Here you are now thinking "inside a box" ... except the box is now 3-dimensional!

-- 
David.


> user system elapsed
> 0.01 0.00 0.02
> >
>
> On Fri, Apr 22, 2011 at 12:28 PM, David Winsemius <dwinsemius_at_comcast.net
> > wrote:
>
> On Apr 22, 2011, at 12:13 PM, Christine SINOQUET wrote:
>
> Hello,
>
> mat1 only consists of 0s and 1s:
> 0 0 1 0 0 0
> 1 1 0 1 1 0
> 1 1 1 0 1 0
> 0 1 1 0 0 1
> 1 0 0 1 0 0
> 0 1 0 1 0 1
>
> N = 3
> M = 6
>
> I would like to "compress" mat1 every two rows, applying summation
> over the two rows (per column), at each step, to yield:
>
> mat2
> 1 1 1 1 1 0
> 1 2 2 0 1 1
> 1 1 0 2 0 1
>
> > mat[seq(1, nrow(mat), by=2), ]+mat[seq(2, nrow(mat), by=2), ]
> [,1] [,2] [,3] [,4] [,5] [,6]
> [1,] 1 1 1 1 1 0
> [2,] 1 2 2 0 1 1
> [3,] 1 1 0 2 0 1
>
>
>
David Winsemius, MD West Hartford, CT ______________________________________________ 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 Fri 22 Apr 2011 - 19:33:51 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 Fri 22 Apr 2011 - 20:00:34 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.

list of date sections of archive