Re: [S] A particular scalar/matrix product

Christian Keller (ckeller@aicos.com)
Fri, 24 Jul 1998 08:27:05 +0200


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))
> A

, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4

, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8

, , 3
[,1] [,2]
[1,] 9 11
[2,] 10 12

> w <- c(10,20,30)

> B <- sweep(A, 3, w, FUN="*")
> B

, , 1
[,1] [,2]
[1,] 10 30
[2,] 20 40

, , 2
[,1] [,2]
[1,] 100 140
[2,] 120 160

, , 3
[,1] [,2]
[1,] 270 330
[2,] 300 360

> apply(B, c(1,2), FUN=sum)
[,1] [,2]
[1,] 380 500
[2,] 440 560

-- Christian Keller
----------------------------------------------------------
Christian Keller Tel: +41 61 686 98 81
AICOS Technologies AG Fax: +41 61 686 98 88
Efringerstrasse 32 email: ckeller@aicos.com
CH-4057 Basel, Switzerland Web: http://www.aicos.com/
----------------------------------------------------------
-----------------------------------------------------------------------
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