gnikit
gnikit

Reputation: 1291

Appending elements generated by a for loop into an array

I want to generate an array containing all the elements produced by a for loop. I haven't found anything relevant or helpful in the NumPy manual or stackoverflow. This is the problematic part of the code.

import numpy as np

for i in range(0,26):
    d = np.random.uniform(i,i+1.75)
    empty = np.array([])
    all = np.append(empty, d)
    print all

I have tried both append and concatenate, both of them just print 25 arrays but only store to all the last one.

Any help will be greatly appreciated.

Upvotes: 2

Views: 1291

Answers (2)

Martin Hallén
Martin Hallén

Reputation: 1552

@Moses's answer works fine, but you can achieve this directly in numpy. np.random.uniform also takes a size parameter. See documentation. Your code can therefore be simplified to:

all = np.random.uniform(0, 1.75, size=(26,))
all += np.arange(26)

The trick here is to realise that np.random.uniform(0, 1.75) + 1 is the same as np.random.uniform(1, 2.75)

The second line is to account for the indices in your loop. The result will be:

array([  0.82259558,   1.07737171,   3.56331306,   3.44506941,
         5.36435903,   6.43062515,   7.4293016 ,   8.62581585,
         9.64664137,  10.11875821,  10.04800508,  12.03356491,
        13.16818327,  14.12761814,  15.09009053,  15.96770449,
        17.0981378 ,  17.47152708,  18.15557107,  20.13834956,
        21.22972932,  22.15797838,  22.97552168,  23.09385798,
        24.17160732,  25.07440533])

This solution might be a little harder to wrap your head around, but it is a very powerful pattern when you want to do more complicated calculations. Please tell me if you don't understand it. And also, @Moses's solution is also correct!

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78556

Your all should be placed outside the loop, so you can avoid overwriting previously written values and the value should be updated and not reassigned to a new append with empty:

import numpy as np

all = np.array([])
for i in range(0,26):
    d = np.random.uniform(i,i+1.75)
    all = np.append(all, d)
    print all

Upvotes: 1

Related Questions