s-news
[Top] [All Lists]

Re: "cumsum" for matrices

To: "Schwarz,Paul" <PSchwarz@gcrinsight.com>
Subject: Re: "cumsum" for matrices
From: Patrick Burns <pburns@pburns.seanet.com>
Date: Sat, 21 Jan 2006 09:54:21 +0000
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <89C7DEAADB79564DB278694EB2417CCE836DEE@CHOCOLATE.GCRInsight.com>
References: <89C7DEAADB79564DB278694EB2417CCE836DEE@CHOCOLATE.GCRInsight.com>
User-agent: Mozilla Thunderbird 1.0.7 (Windows/20050923)
You can cut out some of the arithmetic by only adding
the last slice:

cumsumA[,,1] <- A[,,1]
for(z in seq(len=dim(A)[3])[-1]) cumsumA[,,z] <- cumsumA[,,z-1] + A[,,z]

Also if the product of the first two dimensions is small relative
to the third dimension, then applying 'cumsum' would be faster.

Patrick Burns
patrick@burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Schwarz,Paul wrote:

Dear S-News readers,

I'm working with 3D array objects created via tapply(), eg., tapply(vec,
list(x,y,z), sum). Using the returned array object, I want to create an
object that is the cumulative sum along the z dimension of the matrices
formed by x and y. So far, the best idea I've come up with is something
like the following, which involves a loop:

A <- array( rep(1:9, 3), c(3,3,3))  # test data array
cumsumA <- array(dim= dim(A))  # empty data array
for(z in 1:dim(A)[3]){cumsumA[,, z] <- apply(A[,, 1:z], c(1,2), sum)}


I suspect, however, that there is a better, more efficient way to do
this. Any suggestions?

Thanks for the help and advice.

-Paul
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu.  To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message:  unsubscribe s-news





<Prev in Thread] Current Thread [Next in Thread>