
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
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