Home > Net >  Utilising for loop and numpy.tile to create an array of alternating values i.e. (1, -3, 5, -7, 9, -1
Utilising for loop and numpy.tile to create an array of alternating values i.e. (1, -3, 5, -7, 9, -1

Time:04-13

Is it possible to combine for loop and numpy.tile to create an alternating incremental array?

CodePudding user response:

numpy.tile(A, reps) constructs an array by repeating A the number of times given by reps. Since you want to alternate values, I don't think it is possible (or at least, preferable) to use this function to achieve your goal.

How about using only a for loop (list comprehension)?

output = [i * (1 if i % 4 == 1 else -1) for i in range(1, 25, 2)]

CodePudding user response:

use resize():

In [38]: np.resize([1,-1], 10) # 10 is the length of result array

Out[38]: array([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1])

for odd length:

In [39]: np.resize([1,-1], 11)

Out[39]: array([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1,  1])
  • Related