The Wayback Machine - https://web.archive.org/web/20240708025823/https://www.geeksforgeeks.org/generate-hadamard-matrix-of-given-order/
Open In App

Generate Hadamard matrix of given order

Last Updated : 22 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

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>


Output

1 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

Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Generate a matrix having each element equal to the sum of specified submatrices of a given matrix
Given a matrix mat[][] of dimensions M*N and an integer K, the task is to generate a matrix answer[][], where answer[i][j] is equal to the sum of all elements mat[r][c][/c] such that r ∈ [i - K, i + K], c ∈ [j - K, j + K], and (r, c) is a valid position in the matrix. Examples: Input: mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, K = 1Output: {{12, 21,
15+ min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Sorting rows of matrix in ascending order followed by columns in descending order
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order. Examples : Input : a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 7 8 9 4 5 6 1 2 3 Input : a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output : 7 8 9 4 5 6 1 2 3 Approach: Traverse all rows one by one and sort rows in ascending o
10 min read
Sorting rows of matrix in descending order followed by columns in ascending order
Given a matrix of distinct elements. The task is to sort the rows of matrix in descending order followed by sorting the columns in ascending order. Examples: Input: a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output: 3 2 1 6 5 4 9 8 7 Input: a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output: 3 2 1 6 5 4 9 8 7 Approach: Traverse all rows one by o
9 min read
Generate a Number in Decreasing order of Frequencies of characters of a given String
Given a string Str of length N, consisting of lowercase alphabets, the task is to generate a number in decreasing order of the frequency of characters in the given string. If two characters have the same frequency, the character with a smaller ASCII value appears first. Numbers assigned to characters {a, b, ...., y, z} are {1, 2, ...., 25, 26} resp
12 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Generate a matrix with each row and column of given sum
Given two arrays row[] and col[] of size N and M respectively, the task is to construct a matrix of dimensions N × M such that the sum of matrix elements in every ith row is row[i] and the sum of matrix elements in every jth column is col[j]. Examples: Input: row[] = {5, 7, 10}, col[] = {8, 6, 8}Output: {{0, 5, 0}, {6, 1, 0}, {2, 0, 8}}Explanation:
7 min read
Generate Circulant Matrix from given Array
Given an array A[], the task is to find the circulant matrix made by this array. A circulant matrix is a square matrix of order N x N, where each column is composed of the same elements, but each column is rotated one element to the bottom relative to the preceding column. It is a particular kind of Toeplitz matrix. Here is the general form of a ci
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg