Re: [S] A particular scalar/matrix product

Prof Brian D Ripley (ripley@stats.ox.ac.uk)
Fri, 24 Jul 1998 08:04:53 +0100 (BST)


On Fri, 24 Jul 1998, Christian Keller wrote:

> D. Wiens <wiens@stat.ualberta.ca> wrote:
>
> >> Given a vector w=(w[1],...,w[p]) and an n by n by p array A,
> >> is there a way, which avoids looping, to compute the sum
> >> of products (= an n by n matrix)
> >> w[1]*A[,,1] + ... + w[p]*A[,,p] ?
> >>
> >> It would be sufficient to have a way to get a new array B containing
> >> the products w[j]*A[,,j], since then apply(B,c(1,2),sum) would give
> >> me what I want.
>
> Here is a possible solution: --> sweep
>
> > A <- array(1:12, dim=c(2,2,3))
> > w <- c(10,20,30)
> > B <- sweep(A, 3, w, FUN="*")
> > apply(B, c(1,2), FUN=sum)
> [,1] [,2]
> [1,] 380 500
> [2,] 440 560

more efficiently,

d <- dim(A)
dim(A) <- c(prod(d[-3]),d[3])
B <- A %*% w
dim(B) <- d[-3]

The relies on the ordering of indices in an array; use aperm if
you needed to change them.

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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