pythonsublistpolar-coordinatescartesian-coordinates

Squaring every single item in a 2D list


So I have a large list of points. I have split those points up into the x coordinates and the y coordinates and then further split them into groups of 1000.

x = [points_Cartesian[x: x + 1000, 0] for x in range(0, len(points_Cartesian), 1000)]

(The y coordinates looks the same but with y instead of x.)

I am trying to turn the cartesian points into polar and to do so I must square every item in x and every item in y.

for sublist1 in x:
   temp1 = []
   for inte1 in sublist1:
       temp1.append(inte1**2)
   xSqua.append(temp1)

After that I add both of the Squared values together and square root them to get rad.

rad = np.sqrt(xSqua + ySqua)

The problem is, I started with 10,000 points and somewhere in this code it gets trimmed down to 1,000. Does anyone know what the error is and how I fix it?


Solution

  • You're already using numpy. You can reshape matrices using numpy.reshape() and square the entire array elementwise using the ** operator on the entire array and your code will be much faster than iterating.

    For example, let's say we have a 10000x3 points_cartesian

    points_Cartesian = np.random.random((10000,2))
    # reshape to 1000 columns, as many rows as required
    xpts = points_Cartesian[:, 0].reshape((-1, 1000)) 
    ypts = points_Cartesian[:, 1].reshape((-1, 1000))
    
    # elementwise square using **
    rad = np.sqrt(xpts**2 + ypts**2)
    ang = np.arctan2(ypts, xpts)
    

    Now rad and ang are 10x1000 arrays.