vectorizing a for loop in numpy/scipy?
Posted
by user248237
on Stack Overflow
See other posts from Stack Overflow
or by user248237
Published on 2010-04-19T19:17:19Z
Indexed on
2010/04/19
19:23 UTC
Read the original article
Hit count: 630
I'm trying to vectorize a for loop that I have inside of a class method. The for loop has the following form: it iterates through a bunch of points and depending on whether a certain variable (called "self.condition_met" below) is true, calls a pair of functions on the point, and adds the result to a list. Each point here is an element in a vector of lists, i.e. a data structure that looks like array([[1,2,3], [4,5,6], ...]). Here is the problematic function:
def myClass:
def my_inefficient_method(self):
final_vector = []
# Assume 'my_vector' and 'my_other_vector' are defined numpy arrays
for point in all_points:
if not self.condition_met:
a = self.my_func1(point, my_vector)
b = self.my_func2(point, my_other_vector)
else:
a = self.my_func3(point, my_vector)
b = self.my_func4(point, my_other_vector)
c = a + b
final_vector.append(c)
# Choose random element from resulting vector 'final_vector'
self.condition_met is set before my_inefficient_method is called, so it seems unnecessary to check it each time, but I am not sure how to better write this. Since there are no destructive operations here it is seems like I could rewrite this entire thing as a vectorized operation -- is that possible? any ideas how to do this?
© Stack Overflow or respective owner