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

AI Thread 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Back
Top