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

Click For Summary
The discussion revolves around creating a matrix of values using a function F(i,j) in a more efficient and elegant manner. The initial approach involves using nested loops to populate a list and then reshaping it into an array. However, participants suggest alternatives that eliminate the need for explicit loops. One effective method involves using NumPy's meshgrid function, which generates coordinate matrices from coordinate vectors, allowing for direct application of the function F on the entire grid. This approach simplifies the code and enhances readability. Additionally, it's noted that using range(n) is equivalent to range(0,n), providing a more concise option for generating indices. Overall, the focus is on optimizing array creation in Python using NumPy.
Dunhausen
Messages
30
Reaction score
0
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:
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:
Technology news on Phys.org
Code:
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:
i,j = numpy.meshgrid(range(0,n), range(0,n))
a = F(i,j)
 
Last edited:
That is excellent! Thank you. :)
 
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.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 20 ·
Replies
20
Views
4K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 14 ·
Replies
14
Views
4K
  • · Replies 25 ·
Replies
25
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 14 ·
Replies
14
Views
5K