0

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?

  • 2
    Please give an example of the output. – sophros Nov 06 '18 at 18:21
  • 1
    You can use `numpy` for this. First `import numpy as np` and then I think you're looking for: `np.array([1, 3, 5])*np.array([[2], [4], [6], [8]])` – pault Nov 06 '18 at 18:24
  • 1
    Possible duplicate of [numpy matrix vector multiplication](https://stackoverflow.com/questions/21562986/numpy-matrix-vector-multiplication) – pault Nov 06 '18 at 18:26

2 Answers2

1

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]])
Rocky Li
  • 4,615
  • 1
  • 10
  • 24
0

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