简体   繁体   English

NumPy - 将向量乘以标量添加到矩阵

[英]NumPy - Adding a vector multiplied by a scalar to a matrix

I'm new to NumPy and try to do the following thing without using loops.我是 NumPy 的新手,并尝试在使用循环的情况下执行以下操作。

I have a (n, n) square matrix A and a vector x with size (1,n), and I would like to add the vector to each row of the matrix, while multiplying the vector by the index of the row.我有一个 (n, n) 方阵 A 和一个大小为 (1,n) 的向量 x,我想将向量添加到矩阵的每一行,同时将向量乘以行的索引。
That is, adding the vector * 1 to the first line, the vector * 2 to the second line and so on.即,将向量 *1 添加到第一行,将向量 *2 添加到第二行,依此类推。
Again, loops are not allowed, only NumPy functions.同样,不允许循环,只有 NumPy 函数。

For example, given the matrix:例如,给定矩阵:
[[0, 0, 0] [[0, 0, 0]
[0, 0, 0] [0, 0, 0]
[0, 0, 0]] [0, 0, 0]]

and the vector [[1,1,1]]和向量 [[1,1,1]]

I would like to get:我想得到:
[[1, 1, 1] [[1, 1, 1]
[2, 2, 2] [2, 2, 2]
[3, 3, 3]] [3, 3, 3]]

I tried to use repeat in order to create a matrix with the shape of A from x, but couldn't manage the scalar multiplication.我尝试使用重复来从 x 创建一个形状为 A 的矩阵,但无法管理标量乘法。 Is there any helpful function / effective method?有什么有用的function/有效方法吗?

You can use broadcasting to achieve this.您可以使用广播来实现这一点。

A = np.ones((5,5))
x = np.arange(5)
indices = np.arange(5)[None,:].T
A * x + indices

array([[0., 1., 2., 3., 4.],
       [1., 2., 3., 4., 5.],
       [2., 3., 4., 5., 6.],
       [3., 4., 5., 6., 7.],
       [4., 5., 6., 7., 8.]])

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

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