Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Apr 9, 2010 #1
    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):

    for i in range(0,n):
         for j in range(0,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. jcsd
  3. Apr 9, 2010 #2
    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)
    Code (Text):

    i,j = numpy.meshgrid(range(0,n), range(0,n))
    a = F(i,j)
    Last edited: Apr 9, 2010
  4. Apr 10, 2010 #3
    That is excellent! Thank you. :)
  5. Apr 11, 2010 #4
    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