Python NumPy:如何使用方程填充矩阵

时间:2023-02-09 17:46:23

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_i j = f(I,j)来初始化一个矩阵a(这并不重要)

How can I do so concisely avoiding a situation where I have two for loops?

我怎样才能简洁地避免出现两个for循环的情况呢?

2 个解决方案

#1


10  

numpy.fromfunction fits the bill here.

numpy.fromfunction适合这里的账单。

Example from 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]])

#2


1  

One could also get the indexes of your array with numpy.indices and then apply the function f in a vectorized fashion,

还可以使用numpy获取数组的索引。然后用矢量化的方式应用函数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)

#1


10  

numpy.fromfunction fits the bill here.

numpy.fromfunction适合这里的账单。

Example from 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]])

#2


1  

One could also get the indexes of your array with numpy.indices and then apply the function f in a vectorized fashion,

还可以使用numpy获取数组的索引。然后用矢量化的方式应用函数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)