1

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?

1
  • 1
    In your mind, what's the difference between an array of numbers and a vector. Both are 1d numpy arrays. Commented Feb 21, 2022 at 17:39

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

How does this compare, speed wise, to a built in function like numpy.outer?
Interesting question. I'm guessing this is faster but I'll run some benchmarks.
(by the way, numpy broadcasting is builtin, because it's not a Python feature, it's a numpy feature.)
@Connor My benchmarks indicate that for small amounts of data, mine is a bit faster, and for larger data, ours are about the same.
Thanks so much! I would give you a second upvote if I could!
0

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. However, I am not sure which method is faster.

1 Comment

outer is more focused; while the broadcasted approach can be used with other operators. Many of the ufunc, (e.g. np.add) have an outer method that does the same thing. Overall I don't think speed differences are significant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.