3

Basically, s_{i,j} = a_i + b_j

if n=len(a) and m=len(b), then s.shape is (n,m). Thus, the addition above is not commutative.

It involves some hocus pocus:

s = np.tile(a.reshape(n,1),m).reshape(n,m) + np.tile(b,n).reshape(n,m)

but I was wondering if there's already some method in numpy for this. I could not find it.

1
  • 2
    Use a[:,np.newaxis] + b to leverage broadcasting. Commented Mar 22, 2017 at 19:04

2 Answers 2

5

Yes, there actually is. numpy ufuncs have an outer method:

s = np.add.outer(a, b)
Sign up to request clarification or add additional context in comments.

Comments

0

Outer or broadcasting?

TLDR

In my test, broadcasting is better.

Speed

v1 = np.random.random((1_000))
v2 = np.random.random((1_000))

%timeit np.add.outer(v1, v2)
%timeit v1[:, np.newaxis] + v2

# 9.81 µs ± 2.08 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 7.95 µs ± 756 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each

Both code run almost the same, but v1[:, np.newaxis] + v2 might be faster(?)

Numba

from numba import jit

@jit(nopython=True)
def f1(v1, v2):  # throw error
    return np.add.outer(v1, v2)
def f2(v1, v2):  # works
    return v1[:, np.newaxis] + v2

The v1[:, np.newaxis] + v2 is Numba compatible.

Note:

v1[:, np.newaxis] + v2 == v1[:, None] + v2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.