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
I have just noticed that a couple of ='s should be <-'s in my question. Repeating everything with the corrections made does not resolve my questions. -- 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
Murray Jorgensen <maj at stats.waikato.ac.nz> writes:> 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?Ending that with "})" instead should get rid of the syntax error.... There is a "tensor" package on CRAN that would seem to be designed for these types of operations. -- O__ ---- Peter Dalgaard Blegdamsvej 3 c/ /'_ --- Dept. of Biostatistics 2200 Cph. N (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907