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 do wish to add a vector to a matrix, you can do so by selecting where it should go:
In [155]: ma = np.matrix(
...: [[ 1., 1., 1.],
...: [ 1., 1., 1.],
...: [ 1., 1., 1.]])
In [156]: mb = np.matrix([[1,2,3]])
In [157]: ma[1] += mb # second row
In [158]: ma
Out[158]:
matrix([[ 1., 1., 1.],
[ 2., 3., 4.],
[ 1., 1., 1.]])
In [159]: ma[:,1] += mb.T # second column
In [160]: ma
Out[160]:
matrix([[ 1., 2., 1.],
[ 2., 5., 4.],
[ 1., 4., 1.]])
But I'd like to warn that you are not using numpy.matrix
as stated. In fact, you are using numpy.ndarray
because np.ones
returns an ndarray
and not a matrix
.
The adding is still the same, but create some matrices, and you'll find that they behave differently:
In [161]: ma*mb
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
ValueError: matrices are not aligned
In [162]: mb*ma
Out[162]: matrix([[ 6., 6., 6.]])
In [163]: ma*mb.T
Out[163]:
matrix([[ 6.],
[ 6.],
[ 6.]])
In [164]: aa = np.ones((3,3))
In [165]: ab = np.arange(1,4)
In [166]: aa*ab
Out[166]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
In [167]: ab*aa
Out[167]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.