Sum of a n*n matrix with a vector

I checked the broadcast mechanism of python.

In [79]: a = np.array([[1,2],[3,4]])

In [80]: a 
Out[80]: 
array([[1, 2],
       [3, 4]])

In [81]: b = np.array([4,5])

In [82]: b 
Out[82]: array([4, 5])

In [83]: a + b 
Out[83]: 
array([[5, 7],
       [7, 9]])

I am worried about the ambigurity of broadcast. It seems that the vector ‘b’ is treated as a row vector, and then by tiling, it is extended into a matrix. It would be treated as a column vector and the by tiling be extended into a matrix.

This is the so-called ‘C’-convention, right?

This is numpy’s broadcast, not Python’s. Python has no built-in broadcast.

See Broadcasting — NumPy v1.26 Manual.

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimension and works its way left. Two dimensions are compatible when

  1. they are equal, or
  2. one of them is 1.

In this case, the second dimension of b is 1, which makes b broadcastable over a per rule 2.

No, C has no concept of broadcasting. C arrays can only be operated on element by element.

2 Likes