[R] Array multiplication
Murray Jorgensen
maj at stats.waikato.ac.nz
Tue Dec 3 08:53:02 CET 2002
I wanted a sort of matrix product of an array and a matrix.
As there does not seem to be any array multiplication apart from outer()
I proceeded as follows:
lambda <- array(0, c(n,m,d))
# stuff omitted
# zed is an n by m matrix
#
# \lamb.star_{ik}
lamb.star <- matrix(0, nrow=n, ncol=d)
for (i in 1:n) {
for (k in 1:d) {
for (j in 1:m) {
lamb.star[i,k] = lamb.star[i,k] + lambda[i,j,k]*zed[i,j]
}
}
}
# or, alternatively,
lamb.star <- matrix(0, nrow=n, ncol=d)
for (i in 1:n) {
lamb.star[i,] = zed[i,]%*%lambda[i,,]
}
I wanted to do some timings, but system.time() seems not to work on
compound statements.
system.time({
for (i in 1:n) {
for (k in 1:d) {
for (j in 1:m) {
lamb.star[i,k] = lamb.star[i,k] + lambda[i,j,k]*zed[i,j]
}
}
}
)}
gives a syntax error. I suppose there is a much smarter way to do this
sort of stuff and that somebody will show me?
Murray
--
Dr Murray Jorgensen http://www.stats.waikato.ac.nz/Staff/maj.html
Department of Statistics, University of Waikato, Hamilton, New Zealand
Email: maj at waikato.ac.nz Fax 7 838 4155
Phone +64 7 838 4773 wk +64 7 849 6486 home Mobile 021 395 862
More information about the R-help
mailing list