Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Given two numpy.arrays a and b,

c = numpy.outer(a, b)

returns an two-dimensional array where c[i, j] == a[i] * b[j]. Now, imagine a having k dimensions.

  • Which operation returns an array c of dimension k+1 where c[..., j] == a * b[j]?

Additionally, let b have l dimensions.

  • Which operation returns an array c of dimension k+1 where c[..., i1, i2, i3] == a * b[i1, i2, i3]?
share|improve this question
up vote 4 down vote accepted

The outer method of NumPy ufuncs treats multidimensional input the way you want, so you could do

numpy.multiply.outer(a, b)

rather than using numpy.outer.

All solutions suggested here are equally fast; for small arrays, multiply.outer has a slight edge

enter image description here

Code for generating the image:

import numpy
import perfplot


def multiply_outer(data):
    a, b = data
    return numpy.multiply.outer(a, b)


def outer_reshape(data):
    a, b = data
    return numpy.outer(a, b).reshape((a.shape + b.shape))


def tensor_dot(data):
    a, b = data
    return numpy.tensordot(a, b, 0)


perfplot.show(
        setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n, n)),
        kernels=[multiply_outer, outer_reshape, tensor_dot],
        n_range=[2**k for k in range(7)],
        logx=True,
        logy=True,
        )
share|improve this answer

One approach would be using np.outer and then reshape -

np.outer(a,b).reshape((a.shape + b.shape))
share|improve this answer

I think np.tensordot also works

c = np.tensordot(a, b, 0)

inds = np.reshape(np.indices(b.shape), (b.ndim, -1))
for ind in inds.T:
    ind = tuple(ind)
    assert np.allclose(a * b[ind], c[(...,) + ind])
else:
    print('no error')
# no error 
share|improve this answer

I think you're looking for kroneker product

for example

> np.kron(np.eye(2), np.ones((2,2)))

array([[ 1.,  1.,  0.,  0.],
       [ 1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  1.,  1.]])
share|improve this answer

np.einsum is what you are looking for.

c[..., j] == a * b[j]

should be

c = np.einsum('...i,j -> ...ij', a, b)

and c[..., i1, i2, i3] == a * b[i1, i2, i3] should be

c = np.einsum('i,...jkl -> ...ijkl', a, b)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.