I'm trying to perform an element-wise addition between a 2D NumPy array and a 1D array (like adding a row vector to each row of a matrix), but I'm running into a broadcasting error.
import numpy as np
# Create a 2D array with shape (3, 4)
matrix = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
# Create a 1D array with shape (3,) – I intended this to be a row vector
row_vector = np.array([1, 2, 3])
# Try to add the row vector to each row of the matrix
result = matrix + row_vector
When I run, I am getting following error:
ValueError: operands could not be broadcast together with shapes (3,4) (3,)
Any Ideas?
I thought NumPy would automatically broadcast the 1D array across the rows, but it doesn’t work here.
I tried reshaping the row_vector but not sure what the correct shape should be.
Looked at the documentation on broadcasting, but still not fully clear.
Probably you could use np.newaxis or None like below
mat = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
vec = np.array([1,2,3])
print(mat + vec[:,np.newaxis]) # or `print(mat + vec[:,None])`
and you will obtain
[[ 2 3 4 5]
[ 7 8 9 10]
[12 13 14 15]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With