Search code examples
pythonhaar-wavelet

Haar Transform matric from Matlab to Python


i've recreated a code of Haar Tranform matrix from matlab to python it's a success upon entering the value of n for 2 and 4 but when i'm trying to input 8 there's an error

"Traceback (most recent call last): File "python", line 20, in ValueError: shape too large to be a matrix."

here's my code

import numpy as np
import math

n=8 

# check input parameter and make sure it's the power of 2
Level1 = math.log(n, 2)
Level = int(Level1)+1

#Initialization
H = [1]
NC = 1 / math.sqrt(2)    #normalization constant
LP = [1, 1]
HP = [1,-1]

for i in range(1,Level):

  H = np.dot(NC, [np.matrix(np.kron(H, LP)), np.matrix(np.kron(np.eye(len(H)), HP))])


print H

Solution

  • I'm assuming you got the definition of the haar transform from the wikipedia article or a similar source, so I'll try to stick to their notation.

    The problem with your code is that on the wikipedia article a slight abuse of notation is used. In the equation defining H_2N in terms of H_N, two matrices are stacked on top of eachother with brackets around them. Technically, this would be something like an array consisting of 2 arrays, but they mean it to be a single array where the top half of the values is equal to the one matrix and the bottom half equal to the other matrix.

    In your code, the array of two matrices is the following part:

    [np.matrix(np.kron(H, LP)), np.matrix(np.kron(np.eye(len(H)), HP))]
    

    You can make this into a single matrix as described above using the np.concatenate function as follows:

      H = np.dot(NC, np.concatenate([np.matrix(np.kron(H, LP)), np.matrix(np.kron(np.eye(len(H)), HP))]))