Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply every element in numpy.array a with every element in numpy.array b

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]?
like image 311
Nico Schlömer Avatar asked Mar 15 '17 21:03

Nico Schlömer


People also ask

How do you multiply every element in a NumPy array?

You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.

How do you perform matrix multiplication on the NumPy arrays A and B?

If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.


2 Answers

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

np.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 as np
import perfplot


def multiply_outer(a, b):
    return np.multiply.outer(a, b)


def outer_reshape(a, b):
    return np.outer(a, b).reshape((a.shape + b.shape))


def tensor_dot(a, b):
    return np.tensordot(a, b, 0)


b = perfplot.bench(
    setup=lambda n: (np.random.rand(n, n), np.random.rand(n, n)),
    kernels=[multiply_outer, outer_reshape, tensor_dot],
    n_range=[2 ** k for k in range(7)],
)
b.save("out.png")
like image 188
user2357112 supports Monica Avatar answered Nov 12 '22 19:11

user2357112 supports Monica


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

np.outer(a,b).reshape((a.shape + b.shape))
like image 24
Divakar Avatar answered Nov 12 '22 19:11

Divakar