Skip to content
Advertisement

Vectorize else-if statement function using numpy

I have an array of 3 dimensional vectors vec and I want to find a perpendicular vector res_vec to each of those vectors respectively. Using other methods I got some numerically unstable behaviour so I just check for the smallest component of that vector and set it to zero, while exchanging the two components that are left and negating one of them. However, this is not the main concern, it seems to work just right but it is slow.

So my question is, if my code/functionality can be rewritten so I can eliminate the for-loop and vectorize it using some clever numpy-tricks. So far I failed at all attempts doing so.

This is the code:

JavaScript

The array vec contains data of the form (3D row-vectors):

JavaScript

Advertisement

Answer

As your question is about vectorizing your code, you can look at the code below that compares your for loop version (Timer 1, see code below) with Feri’s vectorized version (Timer 2) and the performance is improved significantly. I also found that using boolean indexing (Timer 3) can speed-up your code even more but the code is a little less aesthetic:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement