Skip to content
Prev 140563 / 398506 Next

avoiding loops

Ingmar Visser asks:
Perhaps, but that's not all that difficult for this kind of operation,
surely?  Even portability across platforms should be pretty
manageable.
What I would try first, then is a loop which makes maximum use of
vectorisation. In this case it would be two loops, of course:

d <- dim(A)
for(i in 1:d[1])
  for(j in 1:d[2])
    A[i,j,] <- A[i,j,] * B

But the following non-loop solution might be your best option:

A <- aperm(aperm(A, c(3,1,2)) * as.vector(B), c(2,3,1))

If you can get your head around working with an A array where what is
now the third dimension becomes the first, then you can eliminate the
aperm()s and it becomes about as fast as C code (which it is, in
effect).  Permuting large arrays can be heavy on memory usage.

Bill Venables.