2

I am using numpy arrays in my codes very frequently. Its speed and convenient indexing rules are very useful. Now, I am searching how to avoid 'for' loops in order to make execution time faster. For the simplicity, let's assume that, we have two vectors(named a and b), each has 10 elements. First value of second vector(b) is equal to 1, then each nth value is equal to '(b[n-1]*13+a[n])/14'. With the help of 'for' loop, I can write that like below:

import numpy as np
a = np.random.random(10)
b = np.ones(10)
for i in range(1, b.shape[0]):
    b[i] = (b[i-1]*13 + a[i]) / 14

So, my question is how can I do same thing without for loop and faster? How can I use numpy vectorization to do that operation? Thanks in advance!

Elgin Cahangirov
  • 1,932
  • 4
  • 24
  • 45
  • looks like every loop relies on the loop before it, if you knew one of the later values you could parallelize it at that point, but really this is more of a combinatorial problem that a programming one. – Grady Player Nov 11 '16 at 16:09
  • Possible duplicate of [this question](http://stackoverflow.com/questions/4407984/is-a-for-loop-necessary-if-elements-of-the-a-numpy-vector-are-dependant-upon-t) – jotasi Nov 11 '16 at 16:14
  • 1
    if you have to use for loops, take a look at cython. Especially, for such a simple example, Cython is a great option. – Moritz Nov 11 '16 at 16:18
  • duplicate - http://stackoverflow.com/q/40366430/901925 – hpaulj Nov 11 '16 at 16:28
  • 1
    The question is becoming a FAQ: http://stackoverflow.com/questions/26267809/recursive-definitions-in-pandas/26268338#26268338, http://stackoverflow.com/questions/21336794/python-recursive-vectorization-with-timeseries/21338665#21338665, http://stackoverflow.com/questions/21391467/can-i-use-numpy-to-speed-this-loop/21392496#21392496, http://stackoverflow.com/questions/27568462/trying-to-vectorize-iterative-calculation-with-numpy/27572590#27572590, etc. And those are just *my* answers; there are many more written by others. – Warren Weckesser Nov 11 '16 at 16:33

1 Answers1

-3

Few days ago I was asked same question in an interview ,so I came up with my implementation in java.I used recursion to iterate over an array

public class IterateWithoutLoop {

private int[]arr;
int size;


public IterateWithoutLoop(int[] arr) {      
    this.arr = arr;
    this.size = 0;
}


public static void main(String[] args) {
    int[]arr={1,2,3,4,5};
    int i=0;
    IterateWithoutLoop iterator=new IterateWithoutLoop(arr);
    iterator.iterateOverArray();
}
public void iterateOverArray(){
    if(arr.length!=size){

        System.out.print(arr[size++]+"\t");
        iterateOverArray();         
    }

}

}

  • Although this would be useful on a Java question, your answer is not helpful here because there is virtually no similarity between a numpy solution to this problem and a java solution. – joshmcode Sep 13 '18 at 21:31