Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating array with transformation

How can I repeat the following example sequence:

l = np.array([3,4,5,6,7])

Up to n times, doubling the values on each repetition. So for n=3:

[3, 4, 5, 6, 7, 6,  8, 10, 12, 14, 12, 16, 20, 24, 28]

Is there a simple way avoiding loops with numpy perhaps?

like image 343
yatu Avatar asked Dec 20 '18 17:12

yatu


People also ask

How do you repeat an array in Python?

const repeat = (arr, n) => Array .from ( { length: arr.length * n }, (_, i) => arr [i % arr.length]);

How many repeating elements are there in an array?

This method doesn’t use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements. Traverse the array once.

How do you repeat a transformation in Photoshop?

Each time you tap the T key (while still holding down the other keys) you will get another copy with the transformation applied. 7. Repeat this all the way around. Because it’s repeating that same transformation from the pivot point, that pivot point is really important.

How to use repeat () function in Julia?

The repeat () is an inbuilt function in julia which is used to construct an array by repeating the specified array elements with the specified number of times. repeat (A::AbstractArray, counts::Integer…) A::AbstractArray: Specified array. counts::Integer: Specified number of times each element get repeated.


2 Answers

numpy.outer + numpy.ndarray.ravel:

>>> a = np.array([3,4,5,6,7])                                                                                          
>>> n = 3                                                                                                              
>>> factors = 2**np.arange(n)                                                                                          
>>> np.outer(factors, a).ravel()                                                                                       
array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])

Details:

>>> factors                                                                                                            
array([1, 2, 4])
>>> np.outer(factors, a)                                                                                               
array([[ 3,  4,  5,  6,  7], # 1*a
       [ 6,  8, 10, 12, 14], # 2*a
       [12, 16, 20, 24, 28]]) # 4*a
like image 102
timgeb Avatar answered Sep 28 '22 10:09

timgeb


You can use concatenate and list comprehension using powers of 2 as the multiplicative factor. Here 3 is the number of repetitions you need.

l = np.array([3,4,5,6,7])
final = np.concatenate([l*2**(i) for i in range(3)])
print (final)

array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])
like image 36
Sheldore Avatar answered Sep 28 '22 09:09

Sheldore