Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 215
j x Avatar asked May 29 '15 11:05

j x


People also ask

How do I fill an array in NumPy?

fill() method is used to fill the numpy array with a scalar value. If we have to initialize a numpy array with an identical value then we use numpy. ndarray. fill().

How do you fill a matrix with random numbers in Python?

To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand. Parameters : low : [int] Lowest (signed) integer to be drawn from the distribution.

How do you add a value to a matrix in Python?

If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.


1 Answers

numpy.fromfunction fits the bill here.

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]])
like image 118
jrmyp Avatar answered Oct 17 '22 01:10

jrmyp