user8330379
user8330379

Reputation:

Python: how to multiply each element in a row and a column without looping

In Python, I have a column array and a row array, say, [1, 3, 5] and [2, 4, 6, 8]' and I want to create a matrix of size 4*3 by multiplying each element in both of them. Is it possible to do without looping?

Upvotes: 0

Views: 1156

Answers (2)

Prasan Karunarathna
Prasan Karunarathna

Reputation: 385

You can use the below code

import numpy as np

>>> x1 = np.arange(2,9,2)   # [2,4,6,8]
>>> x2 = np.arange(1,6,2)   # [1,3,5]
>>> result = x1.dot(x2)
>>> print result

Upvotes: 0

Rocky Li
Rocky Li

Reputation: 5958

Vectorized calculation are best done with numpy:

import numpy as np

x = np.arange(1,6,2) # [1,3,5]
y = np.arange(2,9,2) # [2,4,6,8]
x = np.array([x]) # add dimension for transposing.
y = np.array([y])
result = np.dot(x.T, y)

result:

array([[ 2,  4,  6,  8],
       [ 6, 12, 18, 24],
       [10, 20, 30, 40]])

Upvotes: 1

Related Questions