Generate Hadamard matrix of given order
Last Updated :
22 Jun, 2022
Hadamard matrix is a square matrix with the unique property that any two of its rows are orthogonal. In geometric terms that means that the two rows denote two perpendicular vectors and in combinatorial terms, it means that the two rows have matching elements in exactly half places and the other half elements are mismatching.
Some important properties of a Hadamard matrix are:
- The first order Hadamard matrix is {{1}}.
- A Hadamard matrix contains only +1 and -1 as its elements.
- Any 2m order Hadamard matrix can be constructed using 2m-1 order Hadamard matrices in the following way. This facilitates the easy generation of the matrix if we know the lower-order matrices.
H2m
{ {H2m-1 , H2m-1}
{H2m-1, -H2m-1}}
Given a non-negative integer M, the task is to generate a Hadamard matrix of order 2M.
Examples:
Input: M = 2
Output:
1 1 1 1
1 -1 1 -1
1 1 -1 -1
1 -1 -1 1
Input: M = 3
Output:
Hadamard matrix of order 8
Approach: This is a simple implementation based problem. The idea is to use the above relation and iterate from order 1 to 2M to generate a Hadamard matrix of order 2M.
Follow the steps mentioned below to implement the idea.
- Calculate 2M (say N)and store it.
- Declare a matrix of order N.
- Now initializing the 0th column 0th row element of the matrix as 1.
- Subsequently, run a loop that copies the top left quarter in the other quarters with a correct sign following the property of the Hadamard matrix as shown earlier in this article. The size of the matrix grows in each iteration and eventually reaches the order N.
- Finally, display the matrix on the console.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
void generate(int M)
{
// Computing n = 2^M
// using pow() method of Math class
int n = pow(2, M);
// Initializing a matrix of order n
vector<vector<int> > hadamard(n, vector<int>(n));
// Initializing the 0th column and
// 0th row element as 1
hadamard[0][0] = 1;
for (int k = 1; k < n; k += k) {
// Loop to copy elements to
// other quarters of the matrix
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
hadamard[i + k][j] = hadamard[i][j];
hadamard[i][j + k] = hadamard[i][j];
hadamard[i + k][j + k] = -hadamard[i][j];
}
}
}
// Displaying the final hadamard matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << hadamard[i][j] << " ";
}
cout << endl;
}
}
// Driver code
int main()
{
int M = 2;
// Function call
generate(M);
return 0;
}
// This code is contributed by Ishan Khandelwal
Java
// Java code to implement the approach
import java.util.*;
class GFG {
public static void generate(int M)
{
// Computing n = 2^M
// using pow() method of Math class
int n = (int)Math.pow(2, M);
// Initializing a matrix of order n
int[][] hadamard = new int[n][n];
// Initializing the 0th column and
// 0th row element as 1
hadamard[0][0] = 1;
for (int k = 1; k < n; k += k) {
// Loop to copy elements to
// other quarters of the matrix
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
hadamard[i + k][j]
= hadamard[i][j];
hadamard[i][j + k]
= hadamard[i][j];
hadamard[i + k][j + k]
= -hadamard[i][j];
}
}
}
// Displaying the final hadamard matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(hadamard[i][j] + " ");
}
System.out.println();
}
}
// Driver code
public static void main(String[] args)
{
int M = 2;
// Function call
generate(M);
}
}
Python3
# Python3 code to implement the approach
def generate(M):
# Computing n = 2^M
n = 2 ** M
# Initializing a matrix of order n
hadamard = [ [0] * n for _ in range(n)]
# Initializing the 0th column and
# 0th row element as 1
hadamard[0][0] = 1
k = 1
while (k < n):
# Loop to copy elements to
# other quarters of the matrix
for i in range(k):
for j in range(k):
hadamard[i + k][j] = hadamard[i][j];
hadamard[i][j + k] = hadamard[i][j];
hadamard[i + k][j + k] = -hadamard[i][j];
k *= 2
# Displaying the final hadamard matrix
for i in range(n):
for j in range(n):
print(hadamard[i][j], end = " ")
print()
# Driver code
M = 2;
# Function call
generate(M);
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
public class GFG{
public static void generate(int M)
{
// Computing n = 2^M
// using pow() method of Math class
int n = (int)Math.Pow(2, M);
// Initializing a matrix of order n
int[,] hadamard = new int[n, n];
// Initializing the 0th column and
// 0th row element as 1
hadamard[0,0] = 1;
for (int k = 1; k < n; k += k) {
// Loop to copy elements to
// other quarters of the matrix
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
hadamard[i + k,j]
= hadamard[i,j];
hadamard[i,j + k]
= hadamard[i,j];
hadamard[i + k,j + k]
= -hadamard[i,j];
}
}
}
// Displaying the final hadamard matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write(hadamard[i,j] + " ");
}
Console.WriteLine();
}
}
// Driver code
static public void Main (){
int M = 2;
// Function call
generate(M);
}
}
// This code is contributed by hrithikgarg03188.
JavaScript
<script>
// Javascript code to implement the approach
function generate(M)
{
// Computing n = 2^M
// using pow() method of Math class
let n = Math.pow(2, M);
// Initializing a matrix of order n
let hadamard = new Array(n).fill(0).map(() => new Array(n));
// Initializing the 0th column and
// 0th row element as 1
hadamard[0][0] = 1;
for (let k = 1; k < n; k += k) {
// Loop to copy elements to
// other quarters of the matrix
for (let i = 0; i < k; i++) {
for (let j = 0; j < k; j++) {
hadamard[i + k][j]
= hadamard[i][j];
hadamard[i][j + k]
= hadamard[i][j];
hadamard[i + k][j + k]
= -hadamard[i][j];
}
}
}
// Displaying the final hadamard matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
document.write(hadamard[i][j] + " ");
}
document.write("<br>");
}
}
// Driver code
let M = 2;
// Function call
generate(M);
// This code is contributed by gfgking.
</script>
Output1 1 1 1
1 -1 1 -1
1 1 -1 -1
1 -1 -1 1
Time Complexity: O(2M)
Auxiliary Space: O(2M)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read