简体   繁体   English

Python Numpy:向现有矩阵行添加向量

[英]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.我正在使用 Python/Numpy,我想通过添加相应的元素将行向量添加到矩阵的一行,并使用新行更新矩阵。 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] .例如,我有以下 numpy 数组A = array([[1,2,3],[4,5,6], [7,8,9])和向量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):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 :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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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