TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Impulse Response and Discrete Convolution

Impulse Response and Discrete Convolution

A load cell is read at 100 Sa/s100\ \text{Sa/s} and the firmware averages the last five samples to calm the display. A colleague asks two questions: how long after a weight is placed does the reading settle, and what does the averager do to a short knock on the bench? Both answers come from one sequence, the impulse response h[n]h[n] (what the averager outputs when the input is a single 1 followed by zeros), and one operation, convolution. For any LTI system, the output for any input is the input convolved with hh. This lesson is the working engineer's version of Convolution and Impulse Response: by hand, by matrix and by numpy.

From impulses to the convolution sum

Any sequence is a sum of scaled, shifted impulses: x[n]=∑kx[k] δ[n−k]x[n] = \sum_k x[k]\,\delta[n - k]. Linearity lets us push the sum through the system, and time invariance says the response to δ[n−k]\delta[n - k] is h[n−k]h[n - k]. So

y[n]=∑k=−∞∞x[k] h[n−k]=∑k=−∞∞h[k] x[n−k]=(x∗h)[n]y[n] = \sum_{k=-\infty}^{\infty} x[k]\,h[n - k] = \sum_{k=-\infty}^{\infty} h[k]\,x[n - k] = (x * h)[n]

Read the second form as a recipe: the output now is a weighted sum of the present and past inputs, and the weights are the impulse response. For a causal FIR filter with MM taps h[0],…,h[M−1]h[0], \ldots, h[M-1], that is exactly the code running in the firmware.

Flip and slide. To get one output sample y[n]y[n] by hand, flip h[k]h[k] to h[−k]h[-k], slide it by nn, multiply sample by sample with x[k]x[k], and add.

x[k] 0 2 4 2 -1 k h[2 - k] (flipped, shifted to n = 2) 0 2 4 1 k y[2] = 2(0.25) + 1(0.5) - 1(1) = 0 y[n] = (x * h)[n] 0 2 4 2 n

Useful facts.

  • Lengths: an input of LL samples and an impulse response of MM samples give L+M−1L + M - 1 output samples.
  • Sums: ∑ny[n]=(∑nx[n])(∑nh[n])\sum_n y[n] = \left(\sum_n x[n]\right)\left(\sum_n h[n]\right), a quick check on any hand result. The sum of hh is the DC gain.
  • Commutative (x∗h=h∗xx * h = h * x), associative (a cascade of filters is one filter with h1∗h2h_1 * h_2) and distributive (parallel branches add their impulse responses).
  • Step response s[n]=∑k≤nh[k]s[n] = \sum_{k \le n} h[k], the running sum of hh; its final value is the DC gain.
  • FIR systems have a finite hh; IIR systems (with feedback) have an infinite one, such as h[n]=(1−a) anu[n]h[n] = (1 - a)\,a^n u[n] for the exponential smoother y[n]=a y[n−1]+(1−a) x[n]y[n] = a\,y[n-1] + (1 - a)\,x[n].

Worked example: a three-sample input through a three-tap filter

Given: x[n]={2,1,−1} Vx[n] = \{2, 1, -1\}\ \text{V} for n=0,1,2n = 0, 1, 2 and a filter h[n]={1,0.5,0.25}h[n] = \{1, 0.5, 0.25\} (dimensionless) for n=0,1,2n = 0, 1, 2.

Find: y[n]y[n].

Solve: the output has 3+3−1=53 + 3 - 1 = 5 samples:

y[0]=2(1)=2 Vy[1]=2(0.5)+1(1)=2 Vy[2]=2(0.25)+1(0.5)+(−1)(1)=0 Vy[3]=1(0.25)+(−1)(0.5)=−0.25 Vy[4]=(−1)(0.25)=−0.25 V\begin{aligned} y[0] &= 2(1) = 2\ \text{V} \\ y[1] &= 2(0.5) + 1(1) = 2\ \text{V} \\ y[2] &= 2(0.25) + 1(0.5) + (-1)(1) = 0\ \text{V} \\ y[3] &= 1(0.25) + (-1)(0.5) = -0.25\ \text{V} \\ y[4] &= (-1)(0.25) = -0.25\ \text{V} \end{aligned}

Check: ∑y=3.5 V\sum y = 3.5\ \text{V} and (∑x)(∑h)=2 V×1.75=3.5 V\left(\sum x\right)\left(\sum h\right) = 2\ \text{V} \times 1.75 = 3.5\ \text{V}.

Three ways to compute it

python · try it yourself
import numpy as np
from scipy.signal import lfilter
from scipy.linalg import toeplitz

x = np.array([2.0, 1.0, -1.0])
h = np.array([1.0, 0.5, 0.25])

# 1. Direct double loop: the definition
y_loop = np.zeros(len(x) + len(h) - 1)
for n in range(len(y_loop)):
    for k in range(len(h)):
        if 0 <= n - k < len(x):
            y_loop[n] += h[k] * x[n - k]

# 2. Library convolution
y_np = np.convolve(x, h)

# 3. Convolution as a matrix (Toeplitz): y = H x
col = np.concatenate([h, np.zeros(len(x) - 1)])
H = toeplitz(col, np.zeros(len(x)))
y_mat = H @ x

# 4. As a filter (the way firmware runs it); pad the input to flush the filter
y_filt = lfilter(h, [1.0], np.concatenate([x, np.zeros(len(h) - 1)]))

print("loop  :", y_loop)
print("conv  :", y_np)
print("matrix:", y_mat)
print("lfilter:", y_filt)
print("H =\n", H)
print("sum check:", y_np.sum(), "=", x.sum() * h.sum())
loop  : [ 2.    2.    0.   -0.25 -0.25]
conv  : [ 2.    2.    0.   -0.25 -0.25]
matrix: [ 2.    2.    0.   -0.25 -0.25]
lfilter: [ 2.    2.    0.   -0.25 -0.25]
H =
 [[1.   0.   0.  ]
 [0.5  1.   0.  ]
 [0.25 0.5  1.  ]
 [0.   0.25 0.5 ]
 [0.   0.   0.25]]
sum check: 3.5 = 3.5

The matrix form shows why convolution is linear algebra: each column of HH is the impulse response shifted by one more sample. It is also how least-squares deconvolution and equalisers are set up.

The load-cell averager

Back to the opening question. A five-sample moving average has h[n]=0.2h[n] = 0.2 for n=0…4n = 0 \ldots 4, DC gain 1, and a step response that ramps over 5 samples. Its output lags the input by (M−1)/2=2(M-1)/2 = 2 samples (the centre of mass of hh), 20 ms20\ \text{ms} at 100 Sa/s100\ \text{Sa/s}.

python · try it yourself
import numpy as np
from scipy.signal import lfilter

fs = 100.0                                      # Sa/s
h_ma = np.ones(5) / 5                           # 5-sample moving average
a = 0.8                                         # exponential smoother with a similar delay
rng = np.random.default_rng(3)
n = np.arange(80)
weight = np.where(n >= 5, 2.000, 0.0)           # 2.000 kg placed at n = 5
knock = np.where(n == 60, 0.5, 0.0)             # a 0.5 kg knock lasting one sample
x = weight + knock + 0.02 * rng.standard_normal(len(n))

y_ma = lfilter(h_ma, 1.0, x)
y_exp = lfilter([1 - a], [1, -a], x)
s_ma = np.cumsum(h_ma)                          # step response = running sum of h
print("MA step response:", np.round(s_ma, 2), "-> settles after", len(h_ma), "samples =", 1e3 * len(h_ma) / fs, "ms")
print(f"knock peak: raw {x[60] - 2:.3f} kg above the load, MA {y_ma[60:66].max() - 2:.3f} kg, exp {y_exp[60:66].max() - 2:.3f} kg")
z = rng.standard_normal(20000)                  # long noise-only run for the noise gain
print(f"noise std ratio out/in: MA {lfilter(h_ma, 1.0, z).std() / z.std():.3f}, exp {lfilter([1 - a], [1, -a], z).std() / z.std():.3f}")
k99 = int(np.argmax(np.cumsum((1 - a) * a ** np.arange(60)) >= 0.99))
print(f"exponential smoother reaches 99 % after {k99 + 1} samples = {1e3 * (k99 + 1) / fs:.0f} ms")
MA step response: [0.2 0.4 0.6 0.8 1. ] -> settles after 5 samples = 50.0 ms
knock peak: raw 0.467 kg above the load, MA 0.095 kg, exp 0.092 kg
noise std ratio out/in: MA 0.447, exp 0.335
exponential smoother reaches 99 % after 21 samples = 210 ms

The averager settles in exactly 5 samples, while the exponential smoother (an IIR filter with an infinite hh) never quite gets there: 99 % takes 21 samples. In exchange, the smoother removes more white noise: the noise standard deviation is scaled by ∑h2\sqrt{\sum h^2}, which is 1/5=0.45\sqrt{1/5} = 0.45 for the averager and (1−a)/(1+a)=0.33\sqrt{(1-a)/(1+a)} = 0.33 for the smoother, as the long noise run confirms. A one-sample knock becomes a five-sample bump one fifth as high: convolution spreads it out by the length of hh.

Guided lab: a moving average on a microcontroller ADC

Hand calculation. Sample a 10 Hz10\ \text{Hz} square wave (00 to 3 V3\ \text{V}) at 1 kSa/s1\ \text{kSa/s} and apply an 8-sample moving average. Each edge becomes a ramp lasting 8 samples (8 ms8\ \text{ms}), the flat parts keep their level (DC gain 1), and the output lags by 3.53.5 samples (3.5 ms3.5\ \text{ms}).

Simulation. Change h_ma above to np.ones(8) / 8, fs to 1000 and the input to a square wave; check the ramp length with np.cumsum(h_ma).

What you would measure. Stream raw and filtered samples over the serial port and plot both. Expect edge ramps of 8±18 \pm 1 samples (the edge falls at a random point between two samples) and plateaus within a few LSB of the raw values. If the plateaus differ by more, the coefficient sum is not 1 (a common bug is dividing by 7 or using integer division too early).

Hazards and safe setup. Generator output set to 00 to 3 V3\ \text{V} (offset and amplitude checked on a scope before connecting), a 1 kΩ1\ \text{k}\Omega series resistor into the ADC pin, board powered from USB only.

Pitfalls

  • Using np.convolve(x, h, 'same') in a real-time comparison: it centres the output and hides the filter's delay.
  • Filtering a block with lfilter and forgetting that the last M−1M - 1 output samples are still in the filter (flush with zeros, or carry the state with zi).
  • Forgetting that the DC gain is ∑h\sum h; filters whose taps do not sum to 1 change the level.
  • Convolving very long signals by loops: use scipy.signal.fftconvolve or oaconvolve (Fast Convolution).

Practice

  1. Convolve {1,2,3}\{1, 2, 3\} with {1,−1}\{1, -1\}.
  2. A filter has h={0.25,0.5,0.25}h = \{0.25, 0.5, 0.25\}. What are its DC gain and its step response?
  3. Two filters h1={1,1}h_1 = \{1, 1\} and h2={1,−1}h_2 = \{1, -1\} are cascaded. What is the overall impulse response?
Answer
  1. {1,1,1,−3}\{1, 1, 1, -3\} (check: sums 6×0=06 \times 0 = 0).
  2. DC gain 1; s[n]={0.25,0.75,1,1,…}s[n] = \{0.25, 0.75, 1, 1, \ldots\}.
  3. h1∗h2={1,0,−1}h_1 * h_2 = \{1, 0, -1\}.

Test yourself

An input of 100 samples is convolved with a 31-tap FIR filter. How many output samples does full convolution give?

  1. 100
  2. 130
  3. 131
  4. 3100

The step response of an LTI system equals

  1. the derivative of hh
  2. the running sum of hh
  3. hh flipped
  4. hh squared

Two filters are cascaded. The overall impulse response is

  1. h1+h2h_1 + h_2
  2. h1h2h_1 h_2 sample by sample
  3. h1∗h2h_1 * h_2
  4. the larger of the two

The output of a 9-tap moving average lags its input by

  1. 1 sample
  2. 4 samples
  3. 4.5 samples
  4. 9 samples