Speeding up (vectorising?) a for loop
We are developing a dynamic visual search experiment, where a number of dots move randomly around the screen. The code involves a series of for loops (an extract from the code is pasted in below). Our issue is that as NStim increases, the time taken to execute the for loops increases, meaning that the dots are moving slower when there are more of them. Is it possible to vectorise the code in order to avoid this problem? (sorry, we have some experience with Matlab but not with Python). We'd really like the dots to move at the same speed!
# Loop through all frames for j in range(NFrames): # For each frame, clear the canvas and then loop through all stimuli myCanvas.clear() for i in range(NStim): # Get the stimulus properties x, y, a, v, r = stimList[i] # Update the position of the stimulus based on the angle and the speed x += v * math.cos(a) y += v * math.sin(a) # If the stimulus leaves the screen, reverse direction by 180 deg (= 1pi radial) if x <= 0 or x >= self.get('width') or y <= 0 or y >= self.get('height'): a = a + math.pi else: # else randomly rotate the stimulus a bit a += (random.random()-.5) * maxRotSpeed # Highlight the targets on the first frame if i < NTarget and j == 0: color = targetColor else: color = normalColor # Draw the stimulus myCanvas.circle(x, y, r, fill=True, color=color) # Store the new stimulus properties back in the stimulus list stimList[i] = x, y, a, v, r # Show the canvas myCanvas.show() # Sleep after the first frame so that the participant can identify the targets if j == 0: self.sleep(firstFrameDur) # Store the coordinates of the stimuli in the last frame, in order to compare # the mouse click responses with the actual positions