Create a numpy matrix with elements as a function of indices

前端 未结 5 927
迷失自我
迷失自我 2020-12-16 21:11

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

An Un-numpy and un-

5条回答
  •  别那么骄傲
    2020-12-16 21:51

    A generic solution would be to use np.fromfunction()

    From the doc:

    numpy.fromfunction(function, shape, **kwargs)

    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))

    Output:

    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.]])
    

    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.

提交回复
热议问题