Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading