Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy matrix plus column vector

I am using numpy.matrix. If I add a 3x3 matrix with a 1x3, or 3x1, vector, I get a 3x3 matrix back.

Should this not be undefined? And if not, what is the explanation to this?

Example:

a = np.matrix('1 1 1; 1 1 1; 1 1 1')
b = np.matrix('1 1 1')
a + b #or a + np.transpose(b)

Output:

matrix([[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]])
like image 602
andershqst Avatar asked Apr 01 '13 13:04

andershqst


1 Answers

This is called "broadcasting". From the manual:

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.

like image 106
NPE Avatar answered Sep 24 '22 21:09

NPE