Python Forum
Trying to replace for loops with numpy
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to replace for loops with numpy
#1
Hello all,

I just recently started working on python, and I am currently working on a Simulation that reads the distances between a ball and the Floor through 11 time steps and finds the minimum. The problem is that the ball and the Floor have different number of Elements, so I am using three for lops to run the program, which takes a long time. The Code is computing the data of a Matrix with 11 rows (for each time step) and 3 collumns (x,y,z axis). I am using the qd database to run this example. Also, the Code runs around 20 Million calculations.

for t in range(tsteps):  # Starting a loop for all time steps

    for i in range(lp1):  # Starting the loop for all the elements in part 1

        el1 = elpart1[i].get_coords()  # This Returns the coordenates of the Elements as an np.ndarray (11 x 3)
        el1_id = elpart1[i].get_id()  # This helps with identifying the Elements 

        for j in range(lp2): # Starting the loop for all elements in part 2

            el2 = elpart2[j].get_coords()
            el2_id = elpart2[j].get_id()

            # Using an equation to find the distances between coordinates of each part:
            dist = ((el2[t, 0] - el1[t, 0])**2 + (el2[t, 1] - el1[t, 1])**2 + (el2[t, 2] - el1[t, 2])**2)**(1/2)

            # Adding the elements to the empty lists that were created before the loops started
            dist_list.append(dist)
            element_pair_list.append([el1_id, el2_id])
How could I replace the for Loops to make the Code run more efficiently? Any help is much appreciated!
Reply


Messages In This Thread
Trying to replace for loops with numpy - by vspoloni - Jul-30-2019, 08:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 625 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,642 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  replace sets of values in an array without using loops paul18fr 7 1,758 Jun-20-2022, 08:15 PM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 3,007 Apr-09-2019, 04:54 PM
Last Post: PhysChem

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020