Home > Enterprise >  How do you Efficiently Multiply a Numpy Vector by an Array of Numbers?
How do you Efficiently Multiply a Numpy Vector by an Array of Numbers?

Time:02-22

If I have an array of values:

numbers = np.array([1, 2, 4, 5])

and a vector:

vector = np.array([1, 0, 1])

How do I multiply the vector by the value array to get the following:

vector_array = np.array([[1, 0, 1], [2, 0, 2], [4, 0, 4], [5, 0, 5]])

I have tried to do this using matmul by doing the following:

vector_array = vector[..., None]@numbers

and:

vector_array = vector.T@numbers

I expect to get column vectors which I can then transpose, however instead I get this output:

Option 1:

vector_array = vector[..., None]@numbers
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)

Option 2:

vector_array = vector.T@numbers
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

How can I force matmul to behave in the expected way and multiply the column vector by the row vector to give me a matrix? Is there another function I should be using?

CodePudding user response:

Use numpy broadcasting:

vector_array = vector * numbers[:, None]

Output:

>>> vector_array
array([[1, 0, 1],
       [2, 0, 2],
       [4, 0, 4],
       [5, 0, 5]])

To understand it, look at numbers[:, None]:

>>> numbers
array([1, 2, 4, 5])

>>> numbers[:, None]
array([[1],
       [2],
       [4],
       [5]])

So basically vector * numbers[:, None] multiplies vector by each element of numbers.

CodePudding user response:

One possibility different from the one given by @richardec is to use numpy.outer:

numpy.outer(numbers, normal) = np.array([[1, 0, 1], [2, 0, 2], [4, 0, 4], [5, 0, 5]])

As required, not sure which of the two methods is faster though.

  • Related