Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a numpy matrix with elements as a function of indices

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

like image 963
Pete Avatar asked Jun 06 '11 15:06

Pete


People also ask

How do I create a matrix in NumPy?

We can create a matrix in Numpy using functions like array(), ndarray() or matrix(). Matrix function by default creates a specialized 2D array from the given input. The input should be in the form of a string or an array object-like.

Which function in NumPy is used to create an identity matrix?

identity() is another function for doing matrix operations in numpy. It returns a square identity matrix of given input size. Parameters : n : [int] Number of rows and columns in the output matrix.

How do I assign an element to a NumPy array?

Element Assignment in NumPy Arrays We can assign new values to an element of a NumPy array using the = operator, just like regular python lists.


1 Answers

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.

like image 60
gaganso Avatar answered Sep 18 '22 20:09

gaganso