[英]Python NumPy: How to fill a matrix using an equation
I wish to initialise a matrix A
, using the equation A_i,j = f(i,j)
for some f
(It's not important what this is). 我希望初始化矩阵A
,对于某些f
使用等式A_i,j = f(i,j)
(这不重要)。
How can I do so concisely avoiding a situation where I have two for loops? 我怎么能这样简洁地避免我有两个for循环的情况?
numpy.fromfunction fits the bill here. numpy.fromfunction适合这里的账单。
Example from doc: 来自doc的示例:
>>> import numpy as np
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
One could also get the indexes of your array with numpy.indices
and then apply the function f
in a vectorized fashion, 也可以使用numpy.indices
获取数组的索引,然后以矢量化方式应用函数f
,
import numpy as np
shape = 1000, 1000
Xi, Yj = np.indices(shape)
A = (2*Xi + 3*Yj).astype(np.int) # or any other function f(Xi, Yj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.