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.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Back
Top