Given p
vectors x1,x2,...,xp
each of dimension d
, what's the best way to compute their tensor/outer/Kruskal product (the p
-array X with entries X[i1,i2,..ip] = x1[i1]x2[i2]...xp[ip])
? Looping is trivial, but stupid. Using repeated calls to outer
works OK, but doesn't seem like the optimal solution (and will get slower as p increases, obviously). Is there a better way?
Edit:
My current best is
array(apply(expand.grid(x1, x2, x3), 1, prod), dim=rep(d, 3))
which at least "feels better"...
Edit 2: In response to @Dwin, here's a complete example
d=3
x1 = 1:d
x2 = 1:d+3
x3 = 1:d+6
array(apply(expand.grid(x1, x2, x3), 1, prod), dim=rep(d, 3))
, , 1
[,1] [,2] [,3]
[1,] 28 35 42
[2,] 56 70 84
[3,] 84 105 126
, , 2
[,1] [,2] [,3]
[1,] 32 40 48
[2,] 64 80 96
[3,] 96 120 144
, , 3
[,1] [,2] [,3]
[1,] 36 45 54
[2,] 72 90 108
[3,] 108 135 162