SciPy - hadamard() Function



The scipy.linalg.hadamard() method generates a Hadamard matrix, that is, an n x n square matrix having entries of +1 or -1 and rows are mutually orthogonal. A matrix of such size is produced by Sylvester's construction a recursive technique where the matrix size is doubled at each stage. The value of n must be a power of two.

Hadamard matrices are used in a variety of applications such as Walsh-Hadamard transforms, digital signal processing, and error correction codes. They are also used in orthogonal design experiments.

Errors arise when the input n is not a power of two, because this algorithm is supposed to generate Hadamard matrices based on Sylvester's construction, which can only be done for matrix sizes that are powers of two, like 2, 4, 8, 16. An invalid dtype may introduce compatibility issues.

Hadamard matrices can be combined with matrix multiplication to generate Walsh-Hadamard transforms, often used in signal processing. They can also be used with numpy.linalg.svd() to analyze properties of matrices and numpy.dot() to quickly perform orthogonal projections.

Syntax

The syntax for the SciPy hadamard() method is as follows −

.hadamard(n, dtype=None)

Parameters

This method accepts the following parameters −

  • n (int) − Size of the Hadamard matrix (must be a power of 2).

  • dtype (datatype, optional) − Desired data type for the matrix elements. Default is int.

Return Value

H (ndarray) − An nn Hadamard matrix with elements +1 and -1, having orthogonal rows.

Example 1

The Hadamard matrix has only +1 and -1 values, assuring orthogonality in its rows and columns.

The below code is the basic example of the scipy.linalg.hadamard() function to generate a square Hadamard matrix of a given size n, which must be a power of 2. This example generates a 44 Hadamard matrix.

import scipy.linalg
from scipy.linalg import hadamard

# Generate a 4x4 Hadamard matrix
matrix = scipy.linalg.hadamard(4)
print("Hadamard Matrix:")
print(matrix)

When we run above program, it produces following result

Hadamard Matrix:
[[ 1  1  1  1]
 [ 1 -1  1 -1]
 [ 1  1 -1 -1]
 [ 1 -1 -1  1]]

Example 2

The rows in a Hadamard matrix are orthogonal, which means the dot product of any independent rows is equal to zero.

In the below code, the function hadamard() generates a 4 x 4 Hadamard matrix and checks its orthogonality, it calculates dot products of each different row with each other. Since the dot product of orthogonal vector is zero, the output confirms that these rows are orthogonal.

import numpy as np
from scipy.linalg import hadamard

# Generate a 4x4 Hadamard matrix
matrix = hadamard(4)

# Validate orthogonality
for i in range(4):
    for j in range(i+1, 4):
        dot_product = np.dot(matrix[i], matrix[j])
        print(f"Dot product of row {i} and row {j}: {dot_product}")

Following is an output of the above code

Dot product of row 0 and row 1: 0
Dot product of row 0 and row 2: 0
Dot product of row 0 and row 3: 0
Dot product of row 1 and row 2: 0
Dot product of row 1 and row 3: 0
Dot product of row 2 and row 3: 0

Example 3

The below example, shows how 4x4 Hadamard matrix encodes signal like [1, -1, 1, -1] to [0, 4, 0, -4] for transmission. It exactly decodes back [1, -1, 1, -1] using the matrix's orthogonality, ensuring minimal interference.

import numpy as np
from scipy.linalg import hadamard

# Generate a 4x4 Hadamard matrix
matrix = hadamard(4)

# Signals to encode
signals = [1, -1, 1, -1]

# Encode signals using Hadamard matrix
encoded_signals = np.dot(matrix, signals)
print("Encoded Signals:")
print(encoded_signals)

# Decode signals by multiplying with the transpose of Hadamard matrix
decoded_signals = np.dot(matrix.T, encoded_signals) / 4  # Normalize by matrix size
print("Decoded Signals:")
print(decoded_signals)

Output of the above code is as follows

Encoded Signals:
[0 4 0 0]
Decoded Signals:
[ 1. -1.  1. -1.]

Example 4

This example shows the error that arise if incorrect inputs are passed to hadamard(). The algorithm generates Hadamard matrices by Sylvester's construction. So the input parameter n has to be a power of 2, e.g., 2, 4, 8, 16. The non-power-of-two value like n=6 would raise ValueError.

from scipy.linalg import hadamard

try:
    # Attempt to generate a Hadamard matrix with invalid size (not a power of 2)
    matrix = hadamard(6)
    print("Hadamard Matrix:")
    print(matrix)
except ValueError as e:
    print("Error:", e)

Output of the above code is as follows

Error: n must be an positive integer, and n must be a power of 2
scipy_special_matrices_functions.htm
Advertisements