[R] Multiply a 3D-array by a vector (weighted combination of matrices)

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Oct 17 10:25:28 CEST 2007


Hi

you need the tensor library:



 > library(tensor)

 > z <- array(runif(27),rep(3,3))
 > w <- runif(3)
 > w[1]* z[,,1] + w[2]*z[,,2] + w[3]*z[,,3]
           [,1]      [,2]      [,3]
[1,] 1.2700333 1.1920113 0.8015904
[2,] 0.5175217 0.7808569 0.6306053
[3,] 0.8386015 0.6143882 0.6382314
 > tensor(z,w,3,1)
           [,1]      [,2]      [,3]
[1,] 1.2700333 1.1920113 0.8015904
[2,] 0.5175217 0.7808569 0.6306053
[3,] 0.8386015 0.6143882 0.6382314
 >
 > w[1]* z[,,1] + w[2]*z[,,2] + w[3]*z[,,3] - tensor(z,w,3,1)
               [,1] [,2] [,3]
[1,] -2.220446e-16    0    0
[2,]  0.000000e+00    0    0
[3,]  0.000000e+00    0    0
 >




HTH

rksh


On 17 Oct 2007, at 08:58, Yvonnick NOEL wrote:

> Hello,
>
> I would like to compute a weighted combination of matrices.
>
> I have a number of matrices, arranged in a 3D-array, say:
>
> z = array(rep(1:3,c(9,9,9)),c(3,3,3))
>
> so that z[,,1] is my first matrix, and z[,,2] and z[,,3] the second  
> and
> third one, and a vector of coefficients:
>
> w = rep(1/3,3)
>
> I would like to compute:
>
> w[1]* z[,,1] + w[2]*z[,,2] + w[3]*z[,,3]
>
> I could of course do this using a for() loop, but would like to  
> know if
> there is a way to do it in a "vectorized" manner, or any other way  
> that
> is likely to result in faster computation.
>
> Any hint ?
>
> Thank you very much in advance,
>
> YNOEL
>
> ______________________________________________
> 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.

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-help mailing list