# [R] Avoid loop with three-dimensional array

From: Michela Cameletti <michela.cameletti_at_unibg.it>
Date: Mon, 21 Jul 2008 17:05:30 +0200

Dear R users,
I'm trying to find a solution for optimizing my code. I have to run a 50.000 iteration long simulation and it is absolutely necessary to have an optimized code.

I have to do this operation
*sum_t ( t(X_t) %*% A %*% X_t )*

where X_t is a (d*k) matrix which changes in time and A is a constant in time (d*d) matrix.
I have put all my X_t in a three dimensional array X of dimension (d,k,T).

At the moment for computing the sum over time I'm doing a for loop and saving the resulting (k*k) matrix in a list and at the end I sum the T matrices in this list. I'm wondering if there is a better way to do this.

Here an example of what I have to do:

*d=3

k=2
T=4

X = array(rnorm(d*k*T),dim=c(d,k,T))
A = matrix(rnorm(d*d),d,d)

e1 = list()
for (t in 1:T){ #I would like to avoid this

e1[[t]] = t(X[,,t])%*%A%*%X[,,t]
}

```##############################
```

#Function for doing the sum of matrices in a list
```##############################

sumMatrices <- function(matrices){
if (length(matrices) > 2) matrices[[1]] + Recall(matrices[-1])
else matrices[[1]] + matrices[[2]]
```
}
```##############################

```

result = sumMatrices(e1)
*

best
Michela

[[alternative HTML version deleted]]

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. Received on Mon 21 Jul 2008 - 15:23:49 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 21 Jul 2008 - 15:32:01 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.