创建一个具有元素作为索引函数的numpy矩阵 [英] Create a numpy matrix with elements as a function of indices
问题描述
如何创建一个numpy矩阵,其元素是其索引的函数?
例如,一个乘法表:a[i,j] = i*j
How can I create a numpy matrix with its elements being a function of its indices?
For example, a multiplication table: a[i,j] = i*j
Un-numpy和un-pythonic将创建一个零数组,然后循环遍历.
An Un-numpy and un-pythonic would be to create an array of zeros and then loop through.
毫无疑问,有更好的方法可以做到这一点,而无需循环.
There is no doubt that there is a better way to do this, without a loop.
但是,更好的方法是直接创建矩阵.
However, even better would be to create the matrix straight-away.
推荐答案
A generic solution would be to use np.fromfunction()
来自文档:
numpy.fromfunction(function, shape, **kwargs)
通过在每个坐标上执行一个函数来构造数组.这 因此,结果数组在坐标(x,y, z).
Construct an array by executing a function over each coordinate. The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).
下面的行应提供所需的矩阵.
The below line should provide the required matrix.
numpy.fromfunction(lambda i, j: i*j, (5,5))
输出:
array([[ 0., 0., 0., 0., 0.],
[ 0., 1., 2., 3., 4.],
[ 0., 2., 4., 6., 8.],
[ 0., 3., 6., 9., 12.],
[ 0., 4., 8., 12., 16.]])
该函数的第一个参数是可调用的,可为每个坐标执行.如果foo
是您作为第一个参数传递的函数,则foo(i,j)
将是(i,j)
的值.这也适用于更高的尺寸.可以使用shape
参数修改坐标数组的形状.
The first parameter to the function is a callable which is executed for each of the coordinates. If foo
is a function that you pass as the first argument, foo(i,j)
will be the value at (i,j)
. This holds for higher dimensions too. The shape of the coordinate array can be modified using the shape
parameter.
这篇关于创建一个具有元素作为索引函数的numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!