Numeric 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. If it is not "undefined"? And if not, what is the explanation for 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)

Conclusion:

matrix([[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]])
+5
source share
2 answers

This is called a broadcast. From the manual:

"" , numpy . "" , . Broadcasting , C Python. , . , , , .

+7

, , , :

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

, numpy.matrix, . , numpy.ndarray, np.ones ndarray, matrix.

, , , -:

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

All Articles