I have 2 numpy arrays and want to sum them with offset. The sum always have shape of array "a"
a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6])
sumWithRoll(a, b, offset=1)
print(a)
>> [1, 6, 7, 1, 1]
Also if array "b" is long or offset is big enough it should roll over the end of array "a":
a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6, 7, 8])
sumWithRoll(a, b, offset=3)
print(a)
>> [8, 9, 1, 6, 7]
I need this for merging two sound buffers playing in a loop and would like to have fast solution taking less memory.
Edited: I have a solution that looks long:
def sumWithRoll(buffer, indata, idx):
buffLen = len(buffer)
dataLen = len(indata)
if dataLen > buffLen:
indata = indata[0:buffLen]
dataLen = buffLen
idx = idx % buffLen
idx2 = (idx + dataLen) % buffLen
if idx2 <= idx:
idx3 = buffLen - idx
buffer[idx:buffLen] += indata[0:idx3]
buffer[0:idx2] += indata[idx3:buffLen]
else:
buffer[idx:idx2] += indata[:]
I hope there is Pythonic one or two line solution