[R] applying a function over a matrix 2N x M to produce a matrix N x M
David Winsemius
dwinsemius at comcast.net
Fri Apr 22 21:29:36 CEST 2011
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
More information about the R-help
mailing list