简体   繁体   中英

Adding a vector to a specific row of a matrix with numpy

Hey I want to try to solve the following question using numpy: given two quadratic matrices of different sizes and a Textfile with the information of row indices. I want to add the row of the smaller matrix to the row of the bigger matrices at the corresponding indices. For example:

The small matrix is given as

    1 2 3 
    4 5 6
    7 8 9

The big matrix is a zero matrix for example of size 8

    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0

The text file has now the following entries:

    1
    3
    6

Now the first row of the smaller matrix has to be added to the first row of the bigger one. The second row to the third row and the last row added to the sixth row ie

    1 2 3 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 4 5 6 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 7 8 9
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0      

I tried it with a lot of for-loops but it is not working at all.

Lets assume you have 2 matrices:

import numpy as np

m1 = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9,]])
m2 = np.empty([8, 8])
m2.fill(0)

And a list of positions is defined:

li = [1, 3, 6]

The list defines to replace values of the matrix m2 , by the rows of the matrix m1 , at the positions [0][0:2] , [2][2:4] and [5][5:7] .

Values of numpy arrays can be replaced by numpy.put() .
Calculate the indices of the values to be replaced and replace the values:

ri = [(v-1) * m2.shape[1] + v - 1 + j for v in li for j in range(m1.shape[1])]
np.put(m2, ri, m1)

Output:

print(m1)
print(li)
print(m2)
 [[1 2 3] [4 5 6] [7 8 9]] [1, 3, 6] [[1. 2. 3. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 4. 5. 6. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 7. 8. 9.] [0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0.]]

If you don't want to replace the indices, but you wat to add the values to the current matrix, then you have to sum the values in a loop, instead of replacing by np.put :

for i in range(len(ri)):
    m2.flat[ri[i]] += m1.flat[i] 

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