Outer product of a vector with itself M-times

Viewed 433

I would like to create a M-mode, n-dimensional tensor A from a vector x of length n such that

A_[i_1, i_2, ... , i_M] = x[i_1] * x[i_2] * ... * x[i_M].

The code that I have so far is

A=np.multiply.outer(x,x)
for i in range(M-2):
    A=np.multiply.outer(A,x)

I'm rather new to coding in Python so I'm not sure if there is a more compact/convenient way of computing this tensor.

1 Answers

We could make use of np.ix_ to create open grid versions of input array and then feed those to np.multiply.reduce for element-wise multiplication reductions for all of those, like so -

A = np.multiply.reduce(np.ix_(*[x]*M))

Extending to other supporting ufuncs

We could extend this to other ufuncs that have the reduce method. So, for example to perform outer addition, it would be -

np.add.reduce(np.ix_(*[x]*M))

and so on.

For a complete list of ufuncs that support this feature, please refer to the docs. After Grep-ing for those, I got the following ufuncs that support reduce method and hence could leverage the earlier posted approach :

add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, floor_divide, negative, positive, power, remainder, mod, fmod, divmod, absolute, fabs, rint, sign, heaviside, conj, exp, exp2, log, log2, log10, expm1, log1p, sqrt, square, cbrt, reciprocal, gcd, lcm, sin, cos, tan, arcsin, arccos, arctan, arctan2, hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad, rad2deg, bitwise_and, bitwise_or, bitwise_xor, invert, left_shift, right_shift, greater, greater_equal, less, less_equal, not_equal, equal, logical_and, logical_or, logical_xor, logical_not, maximum, minimum, fmax, fmin, isfinite, isinf, isnan, isnat, fabs, signbit, copysign, nextafter, spacing, modf, ldexp, frexp, fmod, floor, ceil, trunc

Related