Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy broadcasting error when trying to add 2D array and 1D array

Tags:

python

numpy

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.

like image 718
Mr. Thomson Avatar asked Oct 24 '25 03:10

Mr. Thomson


1 Answers

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]]
like image 110
ThomasIsCoding Avatar answered Oct 26 '25 04:10

ThomasIsCoding