# [R] vectorizing a matrix computation

Ernesto Jardim ernesto at ipimar.pt
Tue Jul 20 13:17:50 CEST 2004

```On Tue, 2004-07-20 at 10:54, Wolski wrote:
> Hallo Christoph!
>
> Using apply and sweep.
> Both of them accept  as the second argument (MARGIN) a vector which specifies the dimension.
>
> ?apply
> ?sweep.
>
> To specify the subscripts accurately I always need some trials, and to run tests, so I cant you provide with the final solution.
>
> Hope it helps anyway.
>
> Sincerely Eryk.
>
>
>
>
> On 7/20/2004 at 11:31 AM Christoph Lehmann wrote:
>
> >>>Dear R users
> >>>
> >>>I have a 4-dimensional matrix (actually several 3d (x,y, slices)
> >>>matrices appended over time (volumes))
> >>>
> >>>say, e.g. I want to z-transform the data (subtract the mean and divide
> >>>by the std-deviation)
> >>>
> >>>for (slice in 1:slices) {
> >>>     for (x in 1:x.dim) {
> >>>         for (y in 1:y.dim) {
> >>>         t <- as.matrix(my.matrix[x,y,slice,1:volumes])
> >>>         for (vol in 1:volumes) {
> >>>             my.matrix.transformed[x,y,slice,vol] <-
> >>>(my.matrix[x,y,slice,vol] - mean(t))/sqrt(var(t))
> >>>             }
> >>>         }
> >>>     }
> >>>}
> >>>
> >>>how can I vectorize such a function using, one of the *apply functions?
> >>>
> >>>many thanks
> >>>
> >>>Cheers
> >>>
> >>>Christoph
> >>>

Hi,

You may try to use the "continuous indexing". Notice that if you have a
matrix with dim=c(3,3,2,2)

matriz<-array(rnorm(36, 2,2),dim=c(3,3,2,2))

matriz[1:3] calls matriz[,1,1,1]
matriz[4:6] calls matriz[,2,1,1]
matriz[10:12] calls matriz[,1,2,1]

etc

I think you can use that to perform the calculations you want althought
I'm not sure you're vectorizing

vec <- 1:36
fac <- rep(1:12, rep(3,12))
lapply(split(vec, fac), FUN=function(x){(x-mean(x))/sd(x)})

or simply

tapply(c(matriz),fac,FUN=function(x){(x-mean(x))/sd(x)})

Hope it helps

Best regards

EJ

```