# Scipy/numpy 2D array: how to define with a function?

1. Apr 9, 2010

### Dunhausen

I want to make a matrix of values as so:

F(0,0) . . . F(1,n)
.
.
.
F(n,1) . . . F(n,n)

I could of course do it like this

Code (Text):

list=[]
for i in range(0,n):
for j in range(0,n):
list.append(F(i,j))
a=array(list)
a.reshape(n,n)

But I am curious if there is a more elegant way to build an array with the rule Element i,j = F(i,j) ?

When working with 1-d arrays, I am accustomed to their savvy nature eliminating all need for 'for loops' in my code.

Last edited: Apr 9, 2010
2. Apr 9, 2010

### story645

Code (Text):

a = numpy.empty((n+1,n+1))
for i in range(0,n):
for j in range(0,n):
a[i,j] = F(i,j)

or
Code (Text):

i,j = numpy.meshgrid(range(0,n), range(0,n))
a = F(i,j)

Last edited: Apr 9, 2010
3. Apr 10, 2010

### Dunhausen

That is excellent! Thank you. :)

4. Apr 11, 2010

### story645

Also, didn't have chance to edit, but range(n) generates the same list as range(0,n), if you want to be slightly more concise.

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook