0

I am having trouble understanding some discrete wavelet transform code. I found this snippet which is supposed to yield the dwt up to level 3 for a signal of length 8 and calculate the approximation and detail coefficients in place.

import numpy as np

def Haar(x):
    x = x / np.sqrt(2)

    a, b = x[0] + x[1], x[0] - x[1]
    x[0], x[1] = a, b
    for k in range(2,len(x) - 1,2):
        a, b = x[k] + x[k+1], x[k] - x[k+1]
        x[k], x[k+1] = a, b




x = [4, 6, 10, 12, 8, 6, 5, 5]
print('data', x)
m = int(np.log2(len(x)))



def dwt(x, f):
    for i in range(m):
        f(x[0::2 ** i])

    print('output', x)


dwt(x, Haar)

However, the output with Python 3.8 is the same than the input and imo the operations performed in Haar are not passed back to the call site which results in always working on the original data. The code was written for Python 2 so I tested also with python 2.7 but to the same result.

What am I missing here?

CD86
  • 979
  • 10
  • 27
  • 1
    Your first line `x = x / np.sqrt(2)` assigns `x` to a **new** `np.array` so changes to it will obviously not affect the original list passed to the function... You might want to do something like: `for i in range(len(x)): x[i] /= np.sqrt(2)` – Tomerikoo May 25 '20 at 09:48
  • As explained in the accepted answer, you can do something like `x[:] = x / np.sqrt(2)` to actually change the list itself and not assign a new value to the **local** `x` argument – Tomerikoo May 25 '20 at 10:02
  • thank you guys. also this problem resolves itself when using a np.array instead of a list to start with, correct? – CD86 May 25 '20 at 10:20
  • Not sure, still using `x = ...` will assign the local argument a new value, no matter what type it had in the first place... – Tomerikoo May 25 '20 at 10:30
  • @Tomerikoo if you want in function assign value to external/global variable then you have to use `global x` instead of sending it as argument in `def Haar(x)`. But it is more readable to use `return x` and `x = Haar(x)` – furas May 25 '20 at 10:39

0 Answers0