2

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.

1
  • Alright, have you tried anything, done any research? What exactly is the problem? Commented Mar 19, 2020 at 0:03

1 Answer 1

1
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  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.