Skip to content

Array multiplication

2 messages · Murray Jorgensen, Peter Dalgaard

#
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
#
Murray Jorgensen <maj at stats.waikato.ac.nz> writes:
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.