Walsh–Hadamard codes — generate the matrix and simulate in Matlab

In one sentence: Walsh–Hadamard codes are orthogonal binary sequences from a Hadamard matrix — the spreading set used in classic CDMA and many lab demos.

Matlab/Python simulation: Build $latex H_n$ recursively, verify $latex H H^T = nI$, then run the CDMA-style correlation check in the article.

Python

import numpy as np
import matplotlib.pyplot as plt

def hadamard(n):
    H = np.array([[0, 0], [0, 1]], dtype=int)
    while H.shape[0] < n:
        H = np.block([[H, H], [H, 1 - H]])
    return H

N = 8
H = hadamard(N)
pm = 1 - 2 * H.astype(float)
print("G =\n", (pm @ pm.T).astype(int))

lags = np.arange(-(N - 1), N)
ref = pm[0]
for r in range(1, N):
    corr = np.array([np.dot(ref, np.roll(pm[r], k)) for k in range(-(N - 1), N)])
    plt.plot(lags, corr, label="row %d" % r)
plt.xlabel("lag")
plt.ylabel("periodic correlation")
plt.title("Cross-correlation of Walsh row 0 with rows 1..7")
plt.grid(True, alpha=0.3)
plt.legend(fontsize=8)
plt.tight_layout()
plt.show()

# Autocorrelation of one row: strong only at lag 0 for this alphabet length.
acf = np.array([np.dot(pm[1], np.roll(pm[1], k)) for k in lags])
print("acf of row 1 at lag 0, +/-1:", acf[N - 1], acf[N], acf[N - 2])

Matlab

The original Matlab helper is unchanged in spirit. bitand(codeSize,codeSize-1)==0 still enforces a power of two. Invert the bottom-right quadrant at each doubling, exactly as in the Sylvester step above.

function H = generateHadamardMatrix(codeSize)
N = 2;
H = [0 0; 0 1];
if bitand(codeSize, codeSize-1) ~= 0
    error('codeSize must be a power of 2');
end
while N ~= codeSize
    N = N * 2;
    H = repmat(H, [2 2]);
    H(N/2+1:N, N/2+1:N) = ~H(N/2+1:N, N/2+1:N);
end
end
Walsh code cross-correlation
Periodic cross-correlation of Walsh row 0 with rows 1–7. Every curve is zero at lag 0.
Auto Correlation of Walsh Code
Autocorrelation of one Walsh row. Away from lag zero the sidelobes are large, which is why the forward link has to stay synchronous.

See also

[1] Codes used in CDMA
[2] Spread Spectrum Communications – Intro

Leave a Comment