Arthur
Arthur

Reputation: 117

Vector-vector multiplication to create a matrix

I am an IDL user slowly switching to numpy/scipy, and there is an operation that I do extremely often in IDL but cannot manage to reproduce with numpy:

IDL> a = [2., 4]
IDL> b = [3., 5]
IDL> print,a # b
      6.00000      12.0000
      10.0000      20.0000

I'm not even sure of about the name of this operation. Maybe it is obvious how to do it in numpy, but I could not find a simple way.

Upvotes: 2

Views: 2127

Answers (1)

ali_m
ali_m

Reputation: 74262

This is known as the outer product of two vectors. You could use np.outer:

import numpy as np

a = np.array([2, 4])
b = np.array([3, 5])
c = np.outer(a, b)

print(c)
# [[ 6 10]
#  [12 20]]

Assuming that both of your inputs are numpy arrays (rather than Python lists etc.) you also could use the standard * operator with broadcasting:

# you could also replace np.newaxis with None for brevity (see below)
d = a[:, np.newaxis] * b[np.newaxis, :]

You could also use np.dot in combination with broadcasting:

e = np.dot(a[:, None], b[None, :])

Another lesser-known option is to use the .outer method of the np.multiply ufunc:

f = np.multiply.outer(a, b)

Personally I would either use np.outer or * with broadcasting.

Upvotes: 7

Related Questions