HADAMARD

Constructs an n-by-n Hadamard matrix, where n must be a power of 2. A Hadamard matrix is a square matrix whose entries are either +1 or -1 and whose rows are mutually orthogonal.

Excel Usage

=HADAMARD(n)
  • n (int, required): The order of the matrix. Must be a power of 2.

Returns (list[list]): 2D array representing the Hadamard matrix.

Example 1: Hadamard matrix of order 2

Inputs:

n
2

Excel formula:

=HADAMARD(2)

Expected output:

Result
1 1
1 -1
Example 2: Hadamard matrix of order 4

Inputs:

n
4

Excel formula:

=HADAMARD(4)

Expected output:

Result
1 1 1 1
1 -1 1 -1
1 1 -1 -1
1 -1 -1 1
Example 3: Hadamard matrix from single-cell range input

Inputs:

n
8

Excel formula:

=HADAMARD({8})

Expected output:

Result
1 1 1 1 1 1 1 1
1 -1 1 -1 1 -1 1 -1
1 1 -1 -1 1 1 -1 -1
1 -1 -1 1 1 -1 -1 1
1 1 1 1 -1 -1 -1 -1
1 -1 1 -1 -1 1 -1 1
1 1 -1 -1 -1 -1 1 1
1 -1 -1 1 -1 1 1 -1
Example 4: Hadamard matrix of order 1

Inputs:

n
1

Excel formula:

=HADAMARD(1)

Expected output:

1

Python Code

import numpy as np
from scipy.linalg import hadamard as scipy_hadamard

def hadamard(n):
    """
    Construct a Hadamard matrix.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hadamard.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        n (int): The order of the matrix. Must be a power of 2.

    Returns:
        list[list]: 2D array representing the Hadamard matrix.
    """
    try:
        if isinstance(n, list):
            if not n or not isinstance(n[0], list) or not n[0]:
                return "Error: n must be a scalar or single-cell range"
            n = n[0][0]

        try:
            n_val = int(n)
        except (TypeError, ValueError):
            return "Error: n must be an integer"

        if n_val <= 0:
            return "Error: n must be a positive integer"

        if (n_val & (n_val - 1)) != 0:
            return "Error: n must be a power of 2"

        res = scipy_hadamard(n_val)
        return res.tolist()

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

The order of the matrix. Must be a power of 2.