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]])
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.
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