Here is mentioned that appending to numpy array is not an good idea because it requires re-allocation of the array memory and it slows down the code. There are also mentioned some hints how to avoid it. My goal is to create an saw signal, something like this ASCII art: /\/\/\/\
. I've end up with following two codes and I do not know which one is worse. 2nd one uses also itertools.islice
which is also not world's speed recorder as it discussed here. Both codes mixes standard python lists and numpy arrays. Is there a way how can achieve the same but using pure numpy arrays? Or better: is there any general rule which I can use with numpy everywhere where I would use list.append
instead? As I said on 1st page are mentioned some hints but I cannot figure out working solution. I've been thinking about something like list comprehension that will allow me expand the saw
array first which then I could pass to np.hstack
but I do not think this is possible. I've been also thinking about first declaring numpy array with numpy.empty(400)
or np.zeros(400)
but I do not know how to properly assign to them further values and seems that np.empty
is not so completely empty because it contains zero values:
In [106]: x = np.zeros(10)
In [107]: x
Out[107]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [108]: y = np.empty(10)
In [109]: y
Out[109]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
1st
import numpy as np
import matplotlib.pyplot as plt
saw = []
for x in xrange(0, 3):
saw.append(np.hstack((np.linspace(0,1,50), np.linspace(1,0,50))))
saw2 = saw[0]
for x in saw:
saw2 = np.append([saw2], [x])
plt.figure()
plt.plot(np.arange(saw2.size), saw2)
plt.show()
2nd
import numpy as np
from itertools import islice
import matplotlib.pyplot as plt
saw = []
for x in xrange(0, 4):
saw.append(np.hstack((np.linspace(0,1,50), np.linspace(1,0,50))))
saw2 = saw[0]
for x in islice(saw, 1, None, 1):
saw2 = np.append([saw2], [x])
plt.figure()
plt.plot(np.arange(saw2.size), saw2)
plt.show()