1

I am newer to Python (used to work in IDL and MATLAB) and am trying to get used to how Python "indexes" arrays. I am trying to initiate a 7x13 matrix and fill it in a for loop:

def func(theta2, phi2):
    sph = [[[] for l in range(6)] for m in range(12)] 
    for l in range(0,6):
        for m in range(-6,6):
            sph[l,m]=np.real(np.conjugate(sph_harm(m,l,phi2,theta2))*np.sin(theta2))
    return sph

f = func(np.pi/4,np.pi/4)

This results in this error: "TypeError: list indices must be integers, not tuple ". If I remove the [l,m] index on my variable "sph", I only get a 1x1 array output instead of the desired 7x13 array output.

I have also tried removing the for loops all together and combining it all into one line:

def func(theta2, phi2):
    sph = [[np.real(np.conjugate(sph_harm(m,l,phi2,theta2))*np.sin(theta2)) for l in range(6)] for m in range(-6,6)]
    return sph
f = func(np.pi/4,np.pi/4)

This resulted in a list of 12, 1x6 arrays which is also not what I wanted.

This is similar to this post: How to initialize a two-dimensional array in Python? but I can't seem to figure out how to correctly implement what was suggested in the responses here.

How would I go about fixing this issue?

Community
  • 1
  • 1
Stellar
  • 25
  • 7

3 Answers3

2

Because question title doesn't mention NumPy (but question body and all answers does) I just put below the code in "pure" Python for anybody who get here from Google and doesn't need NumPy solutions.

m = [[0] * col_count for _ in range(row_count)]

Result:

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
0

change

sph[l,m]=np.real(np.conjugate(sph_harm(m,l,phi2,theta2))*np.sin(theta2))

into

sph[l][m]=np.real(np.conjugate(sph_harm(m,l,phi2,theta2))*np.sin(theta2))

and

>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(range(0,6))
[0, 1, 2, 3, 4, 5]

range(n) gives you a list from 0 to n-1

Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21
  • what do you mean? Stellar wants 7 object writing range(6), that's wrong, and you cannot pure python list contained in another pure python list by [a,b] – Paweł Kordowski Nov 21 '15 at 18:02
0

In NumPy you should not write loops.

Define your m and l, here called x and y,as arrays:

zeros = np.zeros((7, 13))
x = zeros + np.arange(7).reshape(7, 1)
y = zeros + np.arange(-6, 7)

Write your function sph_harm() so that it works with whole arrays. For example:

def sph_harm(x, y, phi2, theta2):
    return x + y * phi2 * theta2

Now, creating your array is much simpler, again working with whole arrays:

def func(theta2, phi2):
    zeros = np.zeros((7, 13))
    x = zeros + np.arange(7).reshape(7, 1)
    y = zeros + np.arange(-6, 7)
    return np.real(np.conjugate(sph_harm(x, y, phi2, theta2)) * np.sin(theta2))

f = func(np.pi/4, np.pi/4)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161