0

The code below allows me to add a vector to each row of a given matrix using Numpy:

import numpy as np
m = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 1, 0])
print("Original vector:")
print(v)
print("Original matrix:")
print(m)
result = np.empty_like(m) 
for i in range(4):
  result[i, :] = m[i, :] + v
print("\nAfter adding the vector v to each row of the matrix m:")
print(result)

How do I perform a similar addition operation, but going column by column? I have tried the following:

import numpy as np
array1 = np.array([[5,5,3],[2,2,3]])
print(array1)
addition = np.array([[1],[1]])
print(addition)
for i in range(3):
    array1[:,i] = array1[:,i] + addition
print(array1)

However, I get the following broadcasting error:

ValueError: could not broadcast input array from shape (2,2) into shape (2)

2 Answers 2

2

Just match the number of dimensions, numpy will broadcast the arrays as needed. In the first example, it should be:

result = m + v.reshape((1, -1))

In the second example, the addition is already 2D so it will be just:

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

1 Comment

@EzerK you're right, it is not. The reason to have the reshape it is to make things more explicit, also handling cases when m is a square matrix
0

You can alternatively, add a dimension via Numpy None syntax and then do the addition:

array1 += addition[:,None]

Comments

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.