简体   繁体   中英

Python Numpy: Adding vector to existing matrix row

I am working with Python/Numpy and I would like to add a row vector to one row of a matrix by adding corresponding elements and update the matrix with the new row. For example, I have the following numpy array A = array([[1,2,3],[4,5,6], [7,8,9]) and the vector v =[1,2,3] . So I want to do the following:

A1=v+r1=array([[2,4,6],[4,5,6], [7,8,9])
A2=v+r2=array([[1,2,3],[5,7,9], [7,8,9])
A3=v+r3=array([[1,2,3],[4,5,6], [8,10,12])

Any help to achieve this is appreciated.

In [74]: A = np.arange(1,10).reshape(3,3); v = np.arange(1,4)                                                        
In [75]: A                                                                                                           
Out[75]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
In [77]: v                                                                                                           
Out[77]: array([1, 2, 3])

Expand A to a (3,3,3):

In [78]: A[None,:,:].repeat(3,0)                                                                                     
Out[78]: 
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]])

Do the same with v :

In [79]: np.eye(3)                                                                                                   
Out[79]: 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
In [80]: np.eye(3)[:,:,None]*v                                                                                       
Out[80]: 
array([[[1., 2., 3.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [1., 2., 3.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [1., 2., 3.]]])

add the two:

In [81]: _78+_80                                                                                                     
Out[81]: 
array([[[ 2.,  4.,  6.],
        [ 4.,  5.,  6.],
        [ 7.,  8.,  9.]],

       [[ 1.,  2.,  3.],
        [ 5.,  7.,  9.],
        [ 7.,  8.,  9.]],

       [[ 1.,  2.,  3.],
        [ 4.,  5.,  6.],
        [ 8., 10., 12.]]])

or in one step:

A+np.eye(3)[:,:,None]*v  

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM