简体   繁体   English

使用 numpy 将向量添加到矩阵的特定行

[英]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.嘿,我想尝试使用 numpy 解决以下问题:给定两个不同大小的二次矩阵和一个包含行索引信息的文本文件。 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大矩阵是一个零矩阵,例如大小为 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.我尝试了很多 for 循环,但它根本不起作用。

Lets assume you have 2 matrices:假设您有 2 个矩阵:

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] .该列表定义将矩阵m2值替换为矩阵m1的行,位于[0][0:2][2][2:4][5][5:7]

Values of numpy arrays can be replaced by numpy.put() . numpy 数组的值可以替换为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 :如果您不想替换索引,但要将值添加到当前矩阵,那么您必须在循环中对这些值求和,而不是用np.put替换:

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

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

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