Discrete Signals

Every sound, picture and sensor reading a computer holds is a list of numbers. Two knobs decide how faithful the list is: how often you measure, and how finely you round.

Learn what a signal is, how a wave becomes a list, what breaks when the list is too short or too coarse, and the geometry that lets us treat a list as a point in space.

Drag Samples down below 12 and watch a fast ripple turn into a slow one that was never there. Then drag Bits down and watch the steps appear. Then we build, piece by piece, the notation, the sampling theorem, the energy of a signal, and the vector geometry of the next 30 lectures.

You need basic algebra and a feel for sine waves. We teach complex numbers, vectors and bases from zero.

Based on Lecture 2 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci. Lecture slides. Every idea is re-taught here in our own words and devices; it follows Lecture 1, the course introduction.

Turn a wave into a list

40
8

Illustrative signal: a 2-cycle wave plus a smaller 5-cycle wave over one window, so 5 cycles need more than 10 samples (Nyquist, Chapter 5). Each sample is rounded to one of 2 to the power Bits levels between −1 and +1. The purple wave is rebuilt from the rounded samples by trigonometric interpolation (keep every frequency the samples can represent, drop the one at exactly half the sample rate) and the error is measured against the orange wave, live, at 400 points.

Chapter 0

Why a Wave Becomes a List

See what your phone really stores when you record your voice, and why two choices decide everything that follows

Open the voice memo app on your phone. Say one word. Press stop. The phone now holds a file with your voice in it. Now imagine opening that file in a text editor. You would find no sound and no wave. You would find numbers, thousands of them for every second you spoke: 0, 3, 11, 24, 31, 22, and on and on.

That list is the recording. When you press play, the phone turns the numbers back into a moving speaker cone. Nothing else is stored. Every song, photo, heartbeat trace and temperature log on a computer is the same kind of object: a list of numbers.

This lecture opens a course on signal processing for machine learning. Before any model can learn from audio, pictures or sensors, it has to read these lists. So the first job is to understand them exactly: what the list holds, what it loses, and how to think about it.

Three words, defined

The lecture starts with the three words of the course name. Digital comes from digitus, the Latin word for finger. You count on your fingers: 1, 2, 3. You cannot hold up 2.7 fingers. A computer is the same. It keeps information only as lists, also called sequences, of numbers.

A signal is a function of one or more variables that carries information about some phenomenon. A function is a rule that gives one output for each input. A voice memo takes one input, the time, and gives one output, the air pressure at the microphone. A photo takes two inputs, the row and the column, and gives the brightness. A video takes three.

Processing means algorithms that change a signal to pull information out of it. Remove the hiss from a call. Find the word that was spoken. Spot a heartbeat that skipped. The course name adds one more phrase, “for machine learning”: a model that reads sound reads the list, never the air.

Two choices every recording must make

The world is smooth. Pressure in the air changes without jumps, and a thermometer slides from 20 to 21 degrees through every value between. A list is not smooth. It has a first number, a second number, and nothing between them. So to turn the world into a list, we must make two choices.

The first is when to look. We measure the wave at regular moments and keep only those readings, called samples. Measure too rarely and fast changes slip between the readings. The second is how to write each reading. A computer cannot store 0.30517… with endless digits, so it rounds to one of a fixed set of allowed values. Allow too few and the rounding is coarse. That rounding is called quantization.

You already played with both choices in the instrument at the top of this page. The rest of this lesson explains each one exactly. Try the device below first, because it shows what the choices cost. Pick a sample rate, pick a bit depth, and watch one tiny slice of a 440 hertz tone (the note A above middle C).

Price a recording

The picture is a 5 millisecond slice of a 440 hertz tone. Each blue dot is one sample. Choose a sample rate and a bit depth, then read what one minute costs.

16

The tone and the slice are illustrative. The arithmetic is exact: numbers per minute = rate × 60, bytes = numbers × bits ÷ 8, for one channel (mono) with no compression. The four rates are common choices for telephony, speech models, compact discs and video soundtracks.

At 44,100 samples per second and 16 bits, one minute of mono sound is 44,100 × 60 = 2,646,000 numbers. Each number takes 2 bytes, so the minute needs 5,292,000 bytes, about 5.3 megabytes. A phone call uses far less, because speech needs less. So the choices are not free. They are a budget, and the next chapters show how to spend it well.

Notice what the device cannot show. The list is only a stand-in for the wave. Two different waves can leave the same list. Understanding when that happens, and when it does not, is the heart of this lecture.

The road

The lecture has 48 slides, and the last one lists references. We follow the rest in order. First the notation for signals, then quantization, then the small set of building-block signals, then sampling and what goes wrong with it, and last the idea that a list is a point in space, which gives us bases and the vocabulary of the whole course.

  1. Three kinds of signal: discrete, continuous and digital, and how to write each.
  2. Quantization: rounding to levels, in audio and in pictures.
  3. Building blocks: the delta, the step, the decaying exponential.
  4. Sinusoids and periodicity: the complex exponential, and when a discrete wave repeats.
  5. Sampling: the sampling period and the Nyquist-Shannon theorem.
  6. Aliasing: the wagon wheel, jagged edges and anti-aliasing filters.
  7. Energy and power: how big a signal is.
  8. Geometry of signals: lists as vectors, inner product, norm, Cauchy-Schwarz.
  9. Bases: describing the same signal with different building blocks.
  10. Orthonormal and Fourier bases: the easy way to change basis.
  11. Field guide: the numbers, the code, where to go next.
Why can a computer not store a smooth wave exactly?

Chapter 1

Three Kinds of Signal

Learn to tell a continuous, a discrete and a digital signal apart, and to write each one with the right brackets

A weather station measures the temperature. A stock exchange reports one closing number each day. Your phone keeps a temperature reading once an hour. All three are signals, and yet they are different kinds of object. The first has a value at every instant. The second has one value per day. The third has values you could write in a notebook without any decimals.

Signal processing keeps these three apart with notation. The lecture gives each kind its own symbol, and the symbols tell you at a glance what is allowed as an input and what comes out. This chapter teaches the symbols, because every later formula uses them.

Discrete: one value per whole number

A discrete signal is a function that takes a whole number as input. We write it with square brackets: x[n]. The input n is called the index, and it can be any integer: … −2, −1, 0, 1, 2, … The output can be a real number or a complex number. The lecture writes this as a map, x[n] : ℤ → ℂ or x[n] : ℤ → ℝ. Here ℤ means the integers, ℝ means the real numbers, and ℂ means the complex numbers, which we meet in Chapter 4. A real signal is just a complex one whose values happen to be real.

One of the lecture’s examples is the average of the Dow Jones index in year n. Year 1990 gives one number, year 1991 gives another, and there is nothing for the year 1990.5. The index n is not a moment in time that flows. It is a position in a list. Sometimes that position means a year, sometimes a sample count, sometimes a pixel column. The signal itself does not say which.

The other example is the triangle signal. It comes with a formula, so we can compute every value by hand.

x[n]
The signal’s value at index n. Give it any whole number and it gives one number back.
n + 5
Shift the index up by 5, so the pattern starts at n = −5 instead of n = 0.
mod 11
Keep only the remainder after dividing by 11, like a clock with 11 hours. The result is always 0 to 10, even for negative inputs.
− 5
Slide the whole thing down by 5, so the values run from −5 to +5 and sit around zero.

Work two values. At n = 0: n + 5 = 5, and 5 mod 11 = 5, so x[0] = 5 − 5 = 0. At n = 6: n + 5 = 11, and 11 mod 11 = 0, so x[6] = 0 − 5 = −5. The signal climbs from −5 to +5 one step at a time, then drops back to −5 and climbs again. It repeats every 11 steps. Try any index in the device below.

Compute the triangle by hand

Each stem is one value of x[n]. Drag the index. The three lines below the picture show the three steps of the formula, with negative indices included.

−6

Exact: the formula from the lecture, x[n] = ((n + 5) mod 11) − 5, with the mathematical convention that a remainder is never negative (so −1 mod 11 is 10, as in Python).

At n = −6 the middle step gives −1 mod 11 = 10, because −1 is one step before the clock’s 0, which is 10. So x[−6] = 10 − 5 = 5, and the pattern continues smoothly into negative time. The signal never ends in either direction.

Continuous: a value at every instant

A continuous signal takes any real number as input. We write it with round brackets: x(t) : ℝ → ℂ or ℝ → ℝ. The input t is a continuous index, usually time. The lecture’s example is the temperature at time t. At 7:00 it is one value, at 7:00 and one second another, and so on through every moment between.

The brackets carry real information. When you see x[n] you know n is a whole number. When you see x(t) you know t can be anything. Mixing them up is a common source of mistakes, so read the brackets before you read the formula.

Digital: whole numbers in, whole numbers out

A digital signal goes one step further. Its index is a whole number, and its value is also a whole number: xdig[n] : ℤ → ℤ. This is the only kind a computer can really hold, because each stored value takes a fixed number of bits. An 8-bit audio sample is a whole number from 0 to 255, or −128 to 127. Chapter 2 shows how a discrete signal becomes digital.

Put the three side by side and the same temperature reading shows its three forms. Slide the probe and see which questions each form can answer.

One temperature, three forms

Choose a form. Then slide the time probe from 0 to 24 hours and read what that form says. Try a time between two whole hours.

7.3

Illustrative: x(t) = 14 + 7 sin(2π(t − 9) / 24) degrees Celsius, t in hours, so the daily peak of 21 degrees falls at 15:00. The discrete signal is one reading per hour, and the digital signal rounds each reading to a whole degree.

In continuous mode the probe at 7.3 hours has an answer. In the other two modes it does not, because n must be whole. That is not a flaw. It is the definition. A discrete signal says nothing about the moments between its samples, and Chapter 5 asks when that silence is harmless.

The pipeline, with shapes

In a real machine the three kinds line up as a pipeline. A sensor produces x(t). A converter reads it every T seconds to make x[n]. It then rounds each value to give xdig[n], the list in memory. In code, a signal is a one-dimensional array, and its length is the number of samples.

pythonimport numpy as np
n = np.arange(-16, 17)               # the index: shape (33,), whole numbers
x = (n + 5) % 11 - 5                 # triangle signal x[n]: shape (33,), values -5 to 5
t = np.linspace(0, 24, 25)           # hourly times: shape (25,)
temp = 14 + 7*np.sin(2*np.pi*(t - 9)/24)   # discrete x[n]: floats
temp_dig = np.round(temp).astype(np.int8)  # digital x_dig[n]: shape (25,), dtype int8
audio_1s = np.zeros(16000, dtype=np.int16) # one second at 16 kHz: shape (16000,)

Notice what the array does not store: the time. The array knows only the positions 0, 1, 2, and so on. To turn a position into a moment you need the sampling period T from Chapter 5.

A temperature log stores one whole-degree reading every hour. Which kind of signal is it, and which symbol fits?

Chapter 2

Quantization: Rounding to Levels

Turn a discrete signal into a digital one by rounding, and measure exactly what each bit buys you

Take a photo of a face and show it in 256 shades of grey. It looks perfect. Now allow only 8 shades. Smooth cheeks break into flat patches. Allow only 2 shades and you have a black and white stencil. The picture still has its shape, but the fine gradations are gone.

Audio does the same thing, and the device below lets you hear it. The lecture shows one recording as a trace at 24 bits, 8 bits and 3 bits. The 24-bit trace is a full, fine wave. The 3-bit trace is a thick comb of spikes: the quiet parts of the wave are crushed onto a few levels. This chapter explains why, and gives you a formula for how much hiss each bit removes.

Rounding to the nearest level

Quantization replaces each sample by the nearest value from a short list of allowed values, called levels. With b bits there are 2b levels, because each extra bit doubles the number of patterns: 1 bit gives 2, 2 bits give 4, 3 bits give 8, and 8 bits give 256. Quantization is what turns a discrete signal x[n] (real values) into a digital signal xdig[n] (whole numbers, the level numbers).

Take signals that live between −1 and +1, a range of width 2. Cut that range into 2b equal bins. The width of one bin is the step size Δ.

Δ
The step size: how far apart two neighbouring levels sit.
2
The width of the whole range, from −1 to +1.
2b
The number of levels with b bits. This is the count of bins.
|error|
The distance between the true sample and the level it was rounded to.
Δ / 2
Half a step. Rounding to the nearest level never moves a value more than half a step.

Work it with 3 bits. There are 8 levels, so Δ = 2 / 8 = 0.25. The levels sit at ±0.125, ±0.375, ±0.625 and ±0.875. A sample of 0.30 lies between 0.125 and 0.375. It is closer to 0.375, so it becomes 0.375, an error of 0.075, which is under half a step (0.125). Quantizing a slowly rising triangle signal gives a staircase of equal steps, exactly like the lecture’s figure.

The error is a signal too

The rounding error, true value minus level, is itself a signal. It is the quantization noise. For a busy signal that crosses many bins, the error behaves like a number picked at random and evenly between −Δ/2 and +Δ/2. This is a model, and later chapters of the course test it, but it works well enough to give us a rule.

The average squared size of that error, its power, follows from the even spread. Each error value in the range is equally likely, so the average of e² is the integral of e² / Δ from −Δ/2 to Δ/2, which equals Δ² / 12. A full-scale sine wave with amplitude 1 has average power 1/2. The ratio of signal power to noise power is the signal-to-noise ratio, SNR.

SNR
How many times stronger the wave is than the rounding noise, on a log scale in decibels (dB). Ten times the power is 10 dB.
½
The power of a sine wave of amplitude 1: the average of sin² is one half.
Δ²/12
The noise power from the even-spread model above.
6.02 b + 1.76
Put Δ = 2 / 2b: the ratio becomes 1.5 × 4b. Each added bit multiplies it by 4, which adds 6.02 dB.

So 8 bits give about 6.02 × 8 + 1.76 = 49.9 dB, 16 bits give 98.1 dB and 24 bits give 146.2 dB. That is why a compact disc, with 16 bits, sounds clean. Now test the rule. The device quantizes a sine wave, measures the real noise, and compares it with the formula. It can also play the result.

Round a wave, measure the noise

Top: the orange wave and its blue staircase. Bottom: the red rounding error. Drag Bits down, then drag Loudness down. Press Hear it to listen.

3
100%

Measured: SNR = 10 log10(sum of x² / sum of error²) over 2,400 points of a sine, quantized to mid-rise levels in −1 to +1. The formula is 6.02 b + 1.76 + 20 log10(loudness). The sound is a plucked 220 hertz tone made in your browser, quantized the same way. Keep your volume low.

Watch two things. First, at 1 or 2 bits the measured SNR sits about 1 dB under the formula for a full-scale sine. The error is no longer spread evenly. It follows the wave, and the model starts to fail. Second, drag Loudness down at 8 bits. A wave at 1% of full scale spans only about 2.6 of the 256 levels. The SNR falls by 40 dB, so an 8-bit recording of a whisper is as noisy as a 1.4-bit recording of a shout.

That second failure is the practical one. The symptom is a quiet recording that sounds grainy. The measurement is the number of levels the wave actually uses. The fix is to scale the signal up before rounding, or to add bits. Lecture 3 studies the noise in depth, and Lecture 5 on dithering shows a trick that makes the noise sound gentler.

The same rounding in a picture

A picture is a signal with two indices, row and column. Each pixel is one sample. Rounding pixel brightness works just like rounding audio. The lecture shows a photo from 8 bits down to 1 bit. The device uses a made-up image with a smooth shaded ball, which is the hardest thing for few bits to hold.

Fewer shades, flatter picture

Left: 8 bits, 256 shades. Right: the bit depth you choose. Look at the shaded ball and the smooth background.

3

Toy image made by a formula: a 96 by 64 grid, a ball lit from the upper left, and a left to right gradient. Brightness is rounded to the nearest of 2 to the power Bits grey shades. Storage counts pixels times bits.

At 3 bits the ball breaks into 8 flat bands. Each band edge is a place where the true brightness crossed a rounding boundary, so the eye sees a contour that is not in the scene. That is why these artefacts are called false contours. At 1 bit every pixel is black or white, and only the biggest shapes survive.

You add 2 bits to a recording and keep the same loudness. By roughly how much does the signal-to-noise ratio rise?

Chapter 3

Building Blocks: Delta, Step, Decay

Meet three tiny signals, and see how the smallest one can build every other signal

Clap once in an empty hall. You hear a sharp click, then silence. Now press a light switch and leave it on: the room goes from dark to bright and stays bright. Now pluck a guitar string and let it ring: loud at first, then fading toward nothing. These are three shapes in time, and signal processing gives each a name and a symbol.

They matter for a deeper reason too. Each is simple enough to analyse by hand, and together they let us describe almost any signal. The first one, the click, is the most important. Let us start there.

The delta: a single spike

The delta sequence, also called the unit impulse, is the signal that is 1 at index 0 and 0 everywhere else. It is the click in the empty hall: one moment of energy, and nothing before or after.

δ[n]
The delta, a signal with one nonzero sample. It is the Kronecker delta, a different thing from the continuous Dirac delta.
1 if n = 0, 0 if n ≠ 0
One at the origin, zero at every other whole number.

Now shift it. Replace n by n − k, and the spike moves k places to the right. Check with k = 3: δ[n − 3] equals 1 exactly when n − 3 = 0, which means n = 3. So δ[n − 3] is a spike at position 3. A shifted delta is a spike you can place anywhere.

Any signal is a sum of shifted deltas

Here is the first big idea of the lecture. Take any discrete signal. At each position k, put a spike of the right height: height x[k] at position k. Add all the spikes. You get the signal back.

x[n]
The signal we want to build, at index n.
∑k
Add up one term for every position k. A signal with 16 samples needs 16 terms.
x[k]
The height of the spike at position k, copied from the signal itself.
δ[n − k]
A spike of height 1 at position k. It is 1 only when n equals k.

Why is it true? Pick one index n. Every term in the sum is zero except the one with k = n, because only that spike is nonzero at n. That one term is x[n] · 1. The sum acts like a sieve: it lets exactly one number through at each position.

Work a small case. Let x = (2, −1, 3) at n = 0, 1, 2. Then x[n] = 2δ[n] − 1δ[n − 1] + 3δ[n − 2]. At n = 1 the first term is 2 · 0, the second is −1 · 1 and the third is 3 · 0, so the sum is −1, which is x[1]. In the device you can build a signal this way, one spike at a time, and watch the sum fill in.

Build it from spikes

Pale stems are the target signal. Blue stems are the shifted deltas you have added so far. The teal stem is the next one. Choose a signal, then drag the spike count. In Draw mode, drag across the plot to make your own signal.

6
0.80

The triangle is the lecture’s x[n] = ((n + 5) mod 11) − 5, shown at n = 0 to 15 and scaled by 1/5. The Decay slider only changes the decay signal. Everything is computed exactly in your browser.

Notice that the sum matches the target at every index you have already covered, and is zero beyond. After all 16 spikes it matches everywhere. The deltas are a set of building blocks, and every length-16 signal is a recipe over those 16 blocks. Chapter 9 gives this idea its proper name, a basis.

The step: switched on and left on

The unit step u[n] is 0 for negative n and 1 from n = 0 onward. It is the light switch. The step and the delta are close cousins. The step is a stack of deltas: u[n] = δ[n] + δ[n − 1] + δ[n − 2] + … The delta is the change in the step: δ[n] = u[n] − u[n − 1]. Check: at n = 0 this gives 1 − 0 = 1, and at n = 1 it gives 1 − 1 = 0.

The exponential decay: a ring that fades

The third shape is an u[n], with |a| < 1. The step u[n] switches it on at n = 0. After that, each sample is a times the one before. With a = 0.8 the values run 1, 0.8, 0.64, 0.512, 0.41, and so on, falling a fifth every step. The sample halves after about 3.1 steps, because 0.83.1 ≈ 0.5. A plucked string, an echo and a discharging capacitor all follow this rule.

The lecture allows a to be complex. Then an swings and fades at once, a spiral. We build that picture in the next chapter. For now, a negative real a flips the sign at every step, and |a| < 1 is the condition that keeps the signal fading and not growing.

The takeaway. A delta is one spike. A step is a stack of spikes. A decay is a stack of spikes that shrink by a fixed fraction. Because every signal is a sum of shifted deltas, these blocks are the alphabet, and later chapters swap in better alphabets.
Which signal is 1 at n = 5 and 0 everywhere else?

Chapter 4

Sinusoids and When They Repeat

Watch a point walk around a circle to see the complex exponential, and learn the surprising rule for when a sampled wave repeats

A tuning fork rings at one pure pitch. Its pressure wave is a sinusoid: a smooth up and down swing of the shape cos(angle). Almost every signal we meet is a mix of such swings, so the sinusoid is the most important building block after the delta. In discrete time it has one odd feature, and that feature explains most of the strange things in this lecture.

Complex numbers in two paragraphs

A complex number is a pair of ordinary numbers written a + jb. The symbol j means the square root of −1. Think of the pair as a point on a flat map: a steps right, b steps up. The distance from the origin to the point is its size, written |a + jb|, and it equals √(a² + b²).

The key fact is Euler’s formula: ejθ = cos θ + j sin θ. It says that ejθ is the point on the circle of radius 1 at angle θ (in radians, where a full turn is 2π). Its right-left position is cos θ and its up-down position is sin θ. A cosine is therefore the shadow of a point going around a circle. The circle is the picture to keep.

The complex exponential

The lecture’s complex exponential is x[n] = ej(ω0n + φ). At each sample n the angle is ω0n + φ. So the point starts at angle φ and then takes one step of ω0 radians around the circle for every new sample. Its real part is a cosine and its imaginary part is a sine, which is exactly what the lecture’s two plots show.

A real cosine wave needs no imaginary numbers at all, but writing it with two exponentials makes later algebra much easier. Euler gives it directly.

A cos(ω0n + φ)
The real wave. A is the amplitude (how high it swings), φ the phase in radians (where it starts), n the sample number, and ω0 the frequency in radians per sample (how far the point turns each sample).
(A/2) ej(…)
A point walking counter-clockwise, half the height of the wave.
(A/2) e−j(…)
A twin walking clockwise. The two sit as mirror images, so their up-down parts cancel and their left-right parts add to A cos.

The lecture also gives the frequency in cycles per sample: f = ω0 / 2π. If the point turns π/4 radians per sample, a full turn of 2π takes 8 samples, so f = 1/8 cycle per sample. Play with the circle and the stems below. The point on the circle and the stems are the same thing seen two ways.

Walk the circle, read the wave

Left: the point ej(ωn + φ) on the unit circle. Right: its real part, the stems of cos(ωn + φ). Press Play to step n. Drag the frequency, or press a preset.

0.25
0.00

Exact: x[n] = cos(ω0n + φ), amplitude 1, n from 0 to 31 on the plot. The period is found by the rule in this chapter. Each preset sets an exact fraction (M/N)π, so its period is exact too; a slider position counts as a fraction of 100.

When does a discrete wave repeat?

A signal is periodic if some whole number n0 makes x̃[n] = x̃[n − n0] for every n. The smallest such n0 is the period. For a continuous cosine this is automatic: it repeats every 2π / ω. For a sampled cosine it is not, because n0 must be a whole number of samples.

Derive the rule. We need cos(ω0(n + n0)) = cos(ω0n) for every n. That holds exactly when the extra angle ω0n0 is a whole number of full turns: ω0n0 = 2πm for some integer m. Divide through: ω0 = 2πm / n0, a whole-number ratio times 2π. That is the lecture’s theorem: a discrete sinusoid is periodic if and only if ω0 = (M/N)π for whole numbers M and N, since a ratio times 2π is also a ratio times π.

Now find the period. Write M/N in lowest terms. From (M/N)πn0 = 2πm we get n0 = 2mN / M. If M is even, take m = M/2 and the period is N. If M is odd, M cannot divide 2m until m = M, so the period is 2N. Check: ω0 = π/4 has M = 1, N = 4, so the period is 8, matching one full turn in 8 steps. And ω0 = 2π/3 has M = 2, N = 3, so the period is 3.

The surprise is the other half of the theorem. Set ω0 = 1 radian per sample. Then ω0/π = 0.318…, which is not a ratio of whole numbers. No whole n0 brings the point back to its start exactly. The samples come close, but the wave never repeats. A smooth cosine always repeats, and its sampled copy can fail to. Press the 1 radian preset and look at the stems.

Frequencies wrap around

One more fact hides in the algebra. Add 2π to the frequency: cos((ω0 + 2π)n) = cos(ω0n + 2πn) = cos(ω0n), because 2πn is a whole number of turns for any whole n. So a frequency of ω0 + 2π gives exactly the same list as ω0. The set of distinct discrete frequencies is one circle’s worth, 2π wide, and the fastest cosine is at ω0 = π, where the signal flips sign every sample: +1, −1, +1, −1. Past π the wave looks slower again. Try the 1.75π preset: its stems are those of 0.25π. Chapter 6 shows what this wrap does to real recordings.

The signal x[n] = cos(3πn/4) is periodic. What is its period?

Chapter 5

Sampling: How Often Is Often Enough?

Turn a continuous wave into a list by measuring it every T seconds, and find the exact speed that keeps all of it

You whistle a clean note into a microphone, and a program reads the microphone voltage a few thousand times each second. Your question is simple. How many readings per second must it take so that you could, later, redraw the exact wave you whistled? Too few and the readings miss the wiggles. Too many and you waste memory. There is a precise answer.

Sampling, defined

Let xa(t) be the continuous signal, where the subscript a stands for analog. If we read it once every T seconds, the nth number in our list is its value at time nT.

x[n]
The discrete signal: the list we keep.
xa
The continuous signal in the world, with a value at every instant.
nT
The moment of the nth reading, in seconds. T is the sampling period, the gap between readings. Its inverse 1/T is the sampling frequency, the number of readings per second, in hertz (Hz).

If T = 1/8000 second, then 1/T = 8,000 readings per second. This is the rate of a telephone line. It also settles the units problem from Chapter 1: the index n counts readings, and n times T converts a position in the list into seconds.

What a sampled cosine looks like

Sample the pure tone xa(t) = cos(2πf0t), where f0 is its frequency in hertz. Then x[n] = cos(2πf0nT). Compare this with Chapter 4’s cos(ω0n). They match when ω0 = 2πf0T = 2πf0 / fs, where fs = 1/T. In words: the discrete frequency is the continuous frequency measured in turns per reading.

Work it. A 1,000 Hz whistle sampled at 8,000 Hz gives f0/fs = 1/8 turn per reading, so ω0 = 2π/8 = π/4. By Chapter 4 the list repeats every 8 samples, as you would expect: eight readings per cycle. And ω0/π = 1/4 is a ratio of whole numbers, so periodicity holds. Pick fs so that the ratio is not rational and the list never repeats, even though the whistle always does.

The Nyquist-Shannon theorem

The lecture states the answer as a theorem. If x(t) contains no frequencies higher than B hertz, it is completely determined by its samples x[n] spaced T = 1/(2B) seconds apart. Put another way: sample faster than twice the highest frequency, fs > 2B. For one cosine this reads T ≤ 1/(2f0), exactly the lecture’s condition.

Why two readings per cycle? A cycle has a peak and a trough. One reading per cycle cannot tell a fast wave from a flat line. Two give the up and the down. The theorem says that, for a signal built only from frequencies below B, two per cycle at the fastest frequency is enough to pin down the whole wave, with nothing lost.

Chapter 4 gives a second view. The discrete frequency is ω0 = 2πf0/fs. The condition fs > 2f0 says ω0 < π. That is precisely the range of distinct frequencies a list can hold. The sampling theorem and the wrap-around of Chapter 4 are one fact.

“Completely determined” has a concrete meaning: there is a recipe to redraw the wave. Place a smooth bump called a sinc function, sin(πu)/(πu), at each sample, scaled by the sample’s value, and add them. When the theorem’s condition holds, the sum equals the original wave exactly. The device below uses that recipe, so what it draws in purple is all the list knows.

Is the list enough?

Orange: the true tone over 10 milliseconds. Blue dots: the readings. Purple: the wave rebuilt from only those readings. Drag the sample rate down through twice the tone frequency, then try the Nyquist rate with a phase near 0.5.

400
2,400
0.10

Exact: x(t) = cos(2πf0t + φ), samples at t = n / fs, rebuilt by sinc interpolation using 100 samples either side of the window. The error is measured on the middle 80% of the window, where the finite sum is accurate. Tone and rates are illustrative.

Sweep the sample rate from high to low. While fs stays above twice the tone, the purple wave sits on the orange one. Cross twice the tone and the purple wave becomes a slower wave that was never in the signal. That fault is the subject of Chapter 6. Right at the boundary something stranger happens, which is worth working through by hand.

The edge case: exactly twice

Set fs = 2f0. Then the nth sample is cos(πn + φ) = (−1)n cos φ. If φ = 0 the list is +1, −1, +1, −1, and the rebuilt wave is correct. If φ = π/2 the list is all zeros, and the whole tone disappears, because every reading lands on a zero crossing. The symptom is a tone that vanishes. The measurement is a list of zeros. The fix is to sample strictly faster than 2B. This is why practical systems leave a margin: compact disc audio uses 44,100 Hz to keep tones up to about 20,000 Hz, a ratio of 2.2.

The theorem also assumes the signal has no frequency above B. A real microphone signal has tiny amounts of everything. So the real recipe has two parts: filter out what lies above half the rate, then sample. Chapter 6 shows why the filter is not optional.

A signal contains frequencies up to 3,000 Hz. Which sample rate guarantees the samples completely determine it?

Chapter 6

Aliasing: When a Fast Wave Wears a Slow Mask

Learn exactly what goes wrong below the Nyquist rate, from backward wagon wheels to jagged edges, and the filter that prevents it

In an old western, the stagecoach races across the screen and its wheels seem to turn slowly backward. Nothing is wrong with the wheels. A film camera takes pictures at a fixed rate, and the wheels turn almost one full turn between pictures. The eye links each spoke to the nearest spoke in the next picture and sees a small backward step.

This is the wagon-wheel effect, and the lecture uses it as its example of aliasing: when you sample below the Nyquist rate, a fast frequency appears as a slow one. The lecture notes that the human eye behaves like a camera with a sampling period of about 1/25 second. The mask is not random. It follows a rule you can compute.

The rule

Chapter 4 showed that adding 2π to a discrete frequency changes nothing. Now apply it to sampling. Sample cos(2πf0t) at fs = 1/T. Then a tone at f0 + k fs, for any whole k, gives cos(2πf0nT + 2πkn), because fsT = 1. The extra 2πkn is a whole number of turns, so the samples are identical. After sampling, the tones f0, f0 + fs, f0 + 2fs and so on are indistinguishable. They are aliases: names for the same list.

The list then shows the alias nearest to zero. That gives the apparent frequency.

fapparent
The frequency the samples seem to carry. It always lies between 0 and fs/2.
f0
The true tone in the world, in hertz.
fs
The sampling frequency, in hertz.
round(f0 / fs)
The whole number of sample rates to subtract so that the result lands as close to zero as possible.

Work two cases. A 700 Hz tone sampled at 1,000 Hz: 700/1000 = 0.7 rounds to 1, so fapparent = |700 − 1000| = 300 Hz. A 300 Hz tone gives 300 Hz, so the two tones leave the same list. A 5,000 Hz tone sampled at 8,000 Hz: 5000/8000 = 0.625 rounds to 1, so fapparent = |5000 − 8000| = 3,000 Hz. The device below maps every true frequency to its apparent one. Drag the tone across the Nyquist edge and watch the dot fold back.

Where does the tone land?

Horizontal: the true tone. Vertical: the tone the samples show. The line rises, then folds back at half the sample rate, again and again.

5,000
8,000

Exact: fapparent = |f0 − fs · round(f0 / fs)|. The tone and rates are illustrative.

The zigzag has one safe stretch: from 0 up to fs/2 the apparent frequency equals the true one. Past that edge it zigzags down. That edge is the Nyquist frequency, half the sample rate.

The wagon wheel, measured

Now the film. Mark one spoke and let the wheel turn at f revolutions per second while a camera takes fs frames per second. Between frames the wheel turns f/fs of a turn. The eye chooses the shortest way to link the marks, which is the nearest whole number of turns away. So the apparent speed is f − fs · round(f/fs), and now the sign matters: a negative result means backward. At 24 turns per second and 25 frames per second, the wheel turns 0.96 of a turn per frame. The nearest link is 0.04 of a turn backward, so the film shows 24 − 25 = −1 turn per second: a slow backward creep. At 26 turns per second it creeps forward. At exactly 25 the wheel looks frozen.

Film the wheel

Left: the real wheel, smooth. Right: what the camera records, one picture per frame. The strip below lists the first 8 frames. The page runs the film about 8 times slower than life. Drag the turn rate through the frame rate.

24

Illustrative: a wheel with one marked spoke, a camera with perfect frames. The slow-motion factor is for display only. The apparent speed is exact: f − fs · round(f / fs), in turns per second, negative meaning backward.

Aliasing in pictures

The same thing happens in images, where the “time” being sampled is position. A picture of a brick wall or a striped shirt shrunk to a thumbnail grows a swirl of fake bands called a moiré pattern. The lecture shows a checkerboard before and after fixing it, and a castle photo. A thumbnail keeps only every few pixels, so fine stripes alias exactly like fast tones.

The cure is an anti-aliasing filter: blur first, then sample. The blur removes everything finer than the new pixel grid can hold, so nothing is left to alias. The device paints stripes that get finer to the right and shrinks them two ways. The first row keeps every d-th pixel. The second averages d pixels, a crude blur, before keeping one.

Shrink the stripes

Top: 256 pixels of stripes, finer to the right. Middle: keep every d-th pixel. Bottom: average d pixels first. The red tick marks where stripes become finer than the shrunken image can hold.

4

Toy image: one row of 256 pixels, brightness 0.5 + 0.5 cos(phase), stripe frequency rising from 0.02 to 0.5 cycles per pixel. Contrast is the standard deviation of the shrunken brightness values past the red tick. Averaging is a simple box filter; real systems use smoother filters.

Look to the right of the tick. The middle row shows broad bands that look like real, slow stripes. They are not in the image. They are fast stripes in disguise. The bottom row fades to grey. It lost the fine stripes, which could not be kept anyway, but it did not invent false ones. For an eye or a classifier, an honest grey is better than a confident lie.

The lecture ends this topic by pointing at NVIDIA’s Deep Learning Super Sampling, shown beside the older TAA method. The slide gives the name and a side by side picture. In outline, the game draws fewer pixels than the screen holds, and a trained network fills in the rest. That is machine learning doing the reconstruction step, and it is where this course is heading.

What this means in machine learning

A stride-2 layer in a convolutional network keeps every second value. That is a sampler. If the signal reaching it holds fine detail, the detail aliases into the output, just like the middle row above. A blur before the stride is the same anti-aliasing filter. Whenever you subsample data, ask what lives above the new Nyquist frequency.

A recorder samples at 10,000 Hz. A 7,000 Hz whistle gets into the microphone. What does the recording show?

Chapter 7

Energy and Power: How Big Is a Signal?

Measure a signal with one number, and see why a hum that never stops can be quieter than a drum hit that fades

A drummer strikes a snare once. The crack is loud and then gone. A refrigerator hums all night, softly, without end. Which signal holds more “sound”? Add up everything the drum ever did and you get a modest total. Add up everything the fridge ever did and the total never stops growing. Yet the drum is the louder moment.

Both answers are useful, and they have different names. The total over all time is the signal’s energy. The average per moment is its power. This chapter defines both, works them on real examples, and answers the lecture’s open question.

Energy: add up the squares

The energy of a discrete signal is the sum of the squared size of every sample.

Ex
The energy of the signal x. One number for the whole signal.
∑n
Add up one term for every index n, from the far past to the far future.
|x[n]|²
The sample’s size, squared. For a complex sample, |a + jb|² = a² + b².

Why square? A sample of −3 and a sample of +3 are equally strong, and squaring makes both 9, so strong samples never cancel each other. Squaring also matches physics: the energy of a wave grows with the square of its height. And squares are friendly to geometry, as Chapter 8 shows.

The sum may not settle. If it reaches a finite number, the signal has finite energy, and we say it is square summable. If it grows without bound, the energy is infinite.

Take the decaying exponential from Chapter 3 with a = 0.8. Its squared samples are 0.82n = 0.64n. We need the sum S = 1 + 0.64 + 0.64² + … Multiply by 0.64: 0.64S = 0.64 + 0.64² + … Subtract: S − 0.64S = 1, so S = 1/(1 − 0.64) = 2.78. In general E = 1/(1 − |a|²), a finite number, so the decay is square summable. A signal that is 1 forever has energy 1 + 1 + 1 + … = infinity.

Power: the average per sample

For signals that never fade, the lecture defines power as the average energy per sample over an ever wider window.

Px
The power: the typical squared size of one sample.
limN→∞
Let the window grow forever and see what number the average settles at.
1 / (2N + 1)
One over the number of samples in the window, which runs from −N to N. This turns a total into an average.
∑ |x[n]|²
The energy inside the window.

Two quick cases. For the constant 1, the window energy is 2N + 1 and the average is (2N + 1)/(2N + 1) = 1, so P = 1 even though E is infinite. For a cosine cos(ω0n) the squared samples average to 1/2, so P = 1/2. This is the power we used for the sine wave in Chapter 2.

Now the other direction. If E is finite, the window energy can never exceed E, while the divisor 2N + 1 grows without bound, so the average shrinks to zero. That is the lecture’s statement: finite-energy signals always have zero power. The drum hit has energy but no power. The fridge hum has power but no energy.

The lecture’s question

The lecture ends with a question: if a signal is not square summable, can it have finite power? The constant 1 answers it. Its energy is infinite, so it is not square summable, yet its power is exactly 1. So yes. Now go and check for yourself. Pick each signal, drag the window half-width N, and watch the partial energy (blue) and the partial power (purple).

Energy or power?

Choose a signal. Drag N to widen the window from −N to N. The left graph is the energy inside the window. The right graph is that energy divided by 2N + 1. A dashed line marks a limit when there is one.

30

Exact sums computed live. The cosine is cos(0.5n); the ramp is n/50 for n of 0 or more. The decay’s limit E = 1/(1 − 0.64) = 2.78 comes from the geometric series above.

Read the four cases. The decay: energy flattens at 2.78, so power falls toward zero. The constant: energy climbs in a straight line, but power sits at 1. The cosine: energy climbs, and power settles at 0.5. The ramp: both keep climbing, so it has neither finite energy nor finite power. A signal can have finite energy (and then zero power), or finite power above zero (and then infinite energy), or neither.

In code, the finite-list versions are two lines. Real data always arrives as a finite list, so you will almost always compute the power, which is the mean square.

pythonenergy = np.sum(np.abs(x)**2)      # E_x of a finite list
power  = energy / len(x)             # average energy per sample, the mean square
rms    = np.sqrt(power)              # root mean square: the typical sample size
The signal x[n] = 1 for all n has infinite energy. What is its power?

Chapter 8

Signals as Points: Length, Angle and Similarity

Treat a list of numbers as a point in space, so that length, angle and “how alike” become things you can compute

A GPS gives you three numbers: how far east, how far north, how high. Those three numbers are a point in space, and you can ask how far it is from home, or how close it is to another point. Now take one second of speech at 16,000 samples per second. It is 16,000 numbers. Nothing stops you from calling that a point too, in a space with 16,000 directions.

That step looks silly and turns out to be the most useful idea in the lecture. Once a signal is a point, everything we know about points applies. We can measure its size, the angle between two signals, and how alike they are. The rest of the course, from the Fourier transform to neural networks, lives in this picture.

A finite signal is a vector

A finite-length signal of length N is a list of N real or complex numbers. We write it two equivalent ways: as a vector, x = [x0 x1 … xN−1]T (the T means we stand the list upright as a column), or as x[n] for n = 0, …, N − 1. A vector is a point together with the arrow from the origin to it. The space of all such vectors is ℂN for complex entries, or ℝN for real ones.

The zero vector 0 is the origin, the silent signal. The lecture notes that every other vector is defined relative to it: a vector is how far you travel from zero.

Inner product, norm, angle

The inner product of two vectors multiplies them position by position and adds the products. The lecture puts a star, meaning complex conjugate, on the first vector. The conjugate of a + jb is a − jb. For real numbers the star does nothing.

⟨x, y⟩
One number that says how much x and y point the same way. Large and positive: alike. Zero: unrelated. Negative: opposite.
∑k
Add one product for each of the N positions.
xk*
The complex conjugate of the kth entry of x. It makes ⟨x, x⟩ a sum of squared sizes, never a complex mess.
‖x‖
The norm, or ℓ2-norm: the length of the arrow, the distance from zero.
√⟨x, x⟩
The inner product of a vector with itself is ∑|xk|², the length squared. Take the root.

Look at ⟨x, x⟩. It is ∑|xk|², which is exactly the energy from Chapter 7. So the energy of a finite signal is the squared length of its vector. Work an example. Let x = (3, 4). Then ⟨x, x⟩ = 9 + 16 = 25 and ‖x‖ = 5, the familiar 3-4-5 triangle.

In two real dimensions the lecture links the inner product to the angle θ between the vectors: ⟨x, y⟩ = x0y0 + x1y1 = ‖x‖ ‖y‖ cos θ. Why? The law of cosines says the squared distance between the tips is ‖x − y‖² = ‖x‖² + ‖y‖² − 2‖x‖‖y‖cos θ. Expanding the same squared distance in coordinates gives ‖x‖² + ‖y‖² − 2(x0y0 + x1y1). The two must agree, which gives the formula. When θ = π/2 the cosine is zero, so the inner product is zero. We call such vectors orthogonal, written x ⊥ y. Orthogonal means at right angles, and for signals it means the two have nothing in common.

Take x = (3, 4) and y = (4, 3). Then ⟨x, y⟩ = 12 + 12 = 24, both norms are 5, and cos θ = 24/25 = 0.96, an angle of about 16 degrees. Drag the two arrows in the device and watch every number change.

Drag the arrows

Drag the tip of x or y. The purple arrow is the part of x that lies along y. The dashed line is what is left over, and it always meets y at a right angle.

Exact: real vectors in the plane, with ⟨x, y⟩ = x0y0 + x1y1. Units are arbitrary. The bar compares |⟨x, y⟩| with ‖x‖‖y‖, the Cauchy-Schwarz bound.

The Cauchy-Schwarz inequality

Look at the bar in the device. The inner product never grows past the product of the lengths. This is the Cauchy-Schwarz inequality: |⟨x, y⟩| ≤ ‖x‖‖y‖. For two dimensions it is just |cos θ| ≤ 1. It holds in any number of dimensions, and the lecture proves it by optimization. Here is the proof for real vectors, step by step.

Ask how close the multiple t·y can get to x, where t is a number we choose. The squared distance is f(t) = ‖x − ty‖² = ‖x‖² − 2t⟨x, y⟩ + t²‖y‖². A squared distance is never negative, so its smallest value is at least 0. The smallest value occurs where the slope is zero: −2⟨x, y⟩ + 2t‖y‖² = 0, so t* = ⟨x, y⟩ / ‖y‖². Put t* back: f(t*) = ‖x‖² − ⟨x, y⟩² / ‖y‖². This is at least 0, so ⟨x, y⟩² ≤ ‖x‖²‖y‖². Take roots. Equality holds only when f(t*) = 0, that is, when x is a multiple of y. In the same way, the complex case follows by letting t be complex.

The proof also hands us the purple arrow: t*y is the projection of x onto y, the closest point to x along y. The leftover x − t*y is orthogonal to y. We will use that picture again in the next two chapters.

Why this matters for data

Because |cos θ| ≤ 1, the number ⟨x, y⟩ / (‖x‖‖y‖) always lies in −1 to 1, so it is a safe measure of similarity between two signals of any length. Machine learning calls it cosine similarity. It is the number your search engine computes when it compares two embeddings.

The raw inner product does not work as similarity. A loud clip has a large norm, so its inner product with anything is large. The symptom is that loud clips look similar to everything. The measurement is that doubling a clip doubles every inner product. The fix is to divide by the norms.

pythonimport numpy as np
x = np.array([3, 4.0]);  y = np.array([4, 3.0])
inner = np.vdot(x, y)                  # sum(conj(x_k) * y_k) = 24.0; vdot conjugates the first argument
norm_x = np.linalg.norm(x)             # sqrt(sum |x_k|^2) = 5.0
cos_sim = inner.real / (norm_x * np.linalg.norm(y))   # 0.96, always in [-1, 1]
clip = np.zeros(16000)                 # one second at 16 kHz is a vector in R^16000
Which pair of vectors is orthogonal?

Chapter 9

Bases: Same Signal, Different Building Blocks

Describe one signal with different sets of ingredients, and learn how to test whether a set is good enough

A friend asks where you are. You can say “3 blocks east and 4 blocks north.” Or you can say “5 blocks up the long avenue.” The spot on the map is the same. Only the directions you chose to measure along have changed. In the first answer the directions were east and north. In the second there was one direction, the avenue, and a distance along it.

A signal is a point, as Chapter 8 showed. So we can describe it by travelling along any set of directions we like. Choosing the directions is called choosing a basis. The choice matters more than it seems, because a good basis makes hard tasks easy.

What a basis is

The lecture defines a basis for a class of signals as a collection of M signals from that class with this property: every other signal in the class can be written as a weighted sum of them. For length-N signals, take basis signals y(0)[n], …, y(M−1)[n]. Then any x[n] can be written as follows.

x[n]
The signal we want to describe.
∑k
Add up one scaled basis signal for each k.
c[k]
The coefficient of the kth basis signal: how much of it we need. The list c is the signal’s new description, its coordinates in this basis.
y(k)[n]
The kth basis signal, one of the building blocks.

You have already met one basis. In Chapter 3 every signal was a sum of shifted deltas, with c[m] = x[m]. The lecture names it the standard basis, or canonical basis. In two dimensions it is the pair δ0 = (1, 0) and δ1 = (0, 1): east and north. These arrows are also orthogonal, a property we use in the next chapter.

Why change basis at all?

If the standard basis already works, why bother with others? Because the numbers c[k] are what we compute with, and different bases make different tasks easy. The lecture gives four jobs.

The jobWhat we want from c[k]The lecture’s example
CompressMany small or zero values, fewer than x hasStore only the large c[k]
ClassifySpikes in different places for different classesRecognise speakers: each voice has large Fourier coefficients at different frequencies
Separate sourcesSpikes at different k for different sourcesPollution sources across a city, using a spatial group sparse basis
ReconstructThe most important aspects in a few numbersBody images from outside measurements, with wavelets and curvelets that preserve the outlines of tumours

A tiny case shows the point. Take x = (5, 5), a smooth signal. In the standard basis it needs two numbers, 5 and 5. Use instead the basis (1, 1) and (−1, 1) from the lecture, called the Hadamard basis for two dimensions. It equals the Haar wavelet basis in that size. Now c = (5, 0): one number. A smooth pair has become sparse, and sparse means cheap to store.

How to tell whether a set is a basis

Given N signals of length N, how do we know they form a basis? The lecture’s test is linear independence. The signals are linearly independent if the only way to add them up to the zero signal is to use zero weight on each: ∑ βm y(m) = 0 forces every βm = 0. If a nonzero choice works, the set is linearly dependent: one signal is a mix of the others and adds no new direction. N linearly independent length-N signals always form a basis.

Test the lecture’s example, y(0) = (3, 4) and y(1) = (3, −4). Suppose β0(3, 4) + β1(3, −4) = (0, 0). The first coordinate gives 3β0 + 3β1 = 0, so β1 = −β0. The second gives 4β0 − 4β1 = 0, so β1 = β0. Both hold only if β0 = β1 = 0. So the pair is independent, hence a basis.

Now find the coordinates of x = (5, −1) in that basis. We need c0(3, 4) + c1(3, −4) = (5, −1), which means 3c0 + 3c1 = 5 and 4c0 − 4c1 = −1. Then c0 + c1 = 5/3 and c0 − c1 = −1/4. Add and halve: c0 = 17/24 ≈ 0.708. Subtract and halve: c1 = 23/24 ≈ 0.958. Check: 3(0.708) + 3(0.958) = 5 and 4(0.708) − 4(0.958) = −1. In the Hadamard basis the same x has c = (2, −3), since 2(1, 1) − 3(−1, 1) = (5, −1). Try it in the device: three working bases and one broken one.

Same point, new coordinates

Pick a basis. Drag the point x. The path from the origin shows c0 steps along the first basis arrow, then c1 steps along the second. Then pick the broken set.

Exact: coordinates solve c0y(0) + c1y(1) = x by Cramer’s rule. The broken pair has determinant 1·4 − 2·2 = 0, so it reaches only one line. The point starts at (5, −1), the lecture’s pair of examples.

With the broken set the two arrows lie on one line. Every weighted sum stays on that line, so most points cannot be reached. The symptom is a coordinate solver that returns nothing, or numbers that blow up. The measurement is the determinant, which is exactly zero here. The fix is to swap one arrow for a direction that is not on the line. In code, the test is one rank check.

pythonY = np.array([[3, 4], [3, -4]], dtype=float)      # rows are the basis signals y(0), y(1)
is_basis = np.linalg.matrix_rank(Y) == Y.shape[0]   # True: two independent length-2 signals
x = np.array([5.0, -1.0])
c = np.linalg.solve(Y.T, x)                         # coefficients: [0.7083, 0.9583]
x_back = Y.T @ c                                    # sum_k c[k] y(k) = [5., -1.]
Are (1, 2) and (3, 6) a basis for length-2 signals?

Chapter 10

Orthonormal Bases and the Fourier Basis

Read a signal’s coordinates off with one inner product each, and meet the basis of pure tones that the rest of the course builds on

Last chapter, finding the coordinates of one point in the skewed basis (3, 4) and (3, −4) took two equations and some algebra. Imagine doing that for 16,000 samples. There is a far easier way when the arrows are perpendicular and each has length 1. Then each coordinate is just a shadow: the inner product of the point with that arrow. No equations to solve.

This chapter shows why, then builds the most important perpendicular basis in all of signal processing: the one made of pure tones.

Orthonormal: perpendicular and length one

A basis is orthonormal when two conditions hold. First, the signals are mutually orthogonal: ⟨y(k), y(l)⟩ = 0 whenever k ≠ l. Second, each has norm 1: ‖y(k)‖ = 1. The word comes from ortho (right angle) and normal (unit length). The delta basis is orthonormal, since two different spikes share no position and each has length 1.

The lecture then tests (3, 4) and (3, −4). Are they orthogonal? Their inner product is 9 − 16 = −7, not 0, so they are not. Dividing each by its norm 5 makes both length 1, but it does not turn them. Normalising fixes length, never angle. The slide then shows a perpendicular pair, u0 = (3, 1)/√10 and u1 = (1, −3)/√10. These are a different pair of vectors. Check: 3 − 3 = 0, and each has length √(9 + 1)/√10 = 1. To make an orthonormal basis starting from (3, 4), keep that arrow, scale it to (0.6, 0.8), and turn it a quarter turn to get (−0.8, 0.6).

The easy way to change basis

Suppose y(0), …, y(N−1) is orthonormal and x = ∑l c[l] y(l). Take the inner product of both sides with y(k). On the right, every term has the form c[l] ⟨y(k), y(l)⟩. That is 0 unless l = k, and when l = k it is c[k] · 1. So ⟨y(k), x⟩ = c[k]. The lecture turns this into two steps for changing basis.

c[k]
The expansion coefficient: how much of the kth building block the signal contains.
⟨y(k), x⟩
Step 1: take the inner product of the signal with each basis signal. Each one is a shadow of x on that arrow.
x[n]
The signal, rebuilt exactly.
∑ c[k] y(k)[n]
Step 2: scale each basis signal by its coefficient and add them up.

Work it with x = (5, −1) and the orthonormal pair above. Step 1: c[0] = ⟨u0, x⟩ = (15 − 1)/√10 = 4.43 and c[1] = ⟨u1, x⟩ = (5 + 3)/√10 = 2.53. Step 2: 4.43 · (3, 1)/√10 + 2.53 · (1, −3)/√10 = (4.2 + 0.8, 1.4 − 2.4) = (5, −1). It works. Also look at the sizes: 4.43² + 2.53² = 19.6 + 6.4 = 26 = 5² + 1². The energy of x is the same in the new basis. A change of orthonormal basis only turns the point, and a turn never changes length.

The Fourier basis: a basis of pure tones

Now the key example. The lecture defines the normalised Fourier basis for length-N complex signals.

wm[n]
The mth basis signal, a list of N complex numbers, one for each sample n. There are N of them, m = 0 to N − 1.
1/√N
Makes each signal have length 1: N entries of size 1/√N give squared length N · (1/N) = 1.
ej(2π/N) nm
The Chapter 4 complex exponential, with ω0 = 2πm/N: it makes exactly m full turns of the circle across the N samples.

So w0 is flat (zero turns), w1 makes one slow turn across the window, w2 two turns, and so on up to the fastest. They are pure tones, one for each whole number of cycles per window. Are they orthonormal? Compute the inner product of wk and wr. The star flips the sign of the exponent, so ⟨wk, wr⟩ = (1/N) ∑n ej2πn(r−k)/N. If r = k, every term is 1 and the sum is N/N = 1. If r ≠ k, write q = ej2π(r−k)/N, which is not 1 but satisfies qN = 1. The geometric series gives ∑ qn = (1 − qN)/(1 − q) = 0. In pictures, N points spaced evenly around a circle balance and sum to zero. Check N = 4: w0 = (1, 1, 1, 1)/2 and w1 = (1, j, −1, −j)/2, whose inner product is (1 + j − 1 − j)/4 = 0.

The coefficients c[m] = ⟨wm, x⟩ say how much of each tone is in the signal. This is the discrete Fourier transform, to which Lecture 6 is devoted. For now, notice the payoff the lecture promised in Chapter 9. A signal made from a few tones has a few large c[m]. Play with it. Choose a signal, then keep only the K largest Fourier coefficients and rebuild.

Keep the biggest tones

Top: the signal (orange) and the purple rebuild from K Fourier coefficients. Bottom: the size of every coefficient, tallest in pink. Choose a signal, then drag K. Compare Spike with Pure tone.

2

Exact, computed live: c[m] = ⟨wm, x⟩ with the normalised basis, N = 32. Signals: a 3-cycle cosine; a 2-cycle cosine plus half of a 7-cycle one; a square wave of 4 cycles; one spike at n = 10. Real signals give coefficients in mirror pairs, so K counts both members. The rebuild takes the real part. The energy kept is the sum of the kept |c|² over the total, by the energy match shown above.

For a pure tone, two coefficients (the mirror pair) hold 100% of the energy. Rebuilding from two is exact. The spike behaves the opposite way: in the standard basis it is a single number, but in the Fourier basis it spreads over all 32 coefficients equally, each of size 1/√32. No basis wins everywhere. A good basis makes the signals you care about sparse. That is the whole reason to learn many of them, and the reason the lecture lists compressing, classifying, separating and reconstructing as separate goals.

pythonN = 32; n = np.arange(N)
W = np.exp(2j*np.pi*np.outer(n, n)/N) / np.sqrt(N)    # column m is w_m[n]: shape (32, 32)
x = np.cos(2*np.pi*3*n/N)                              # a 3-cycle tone: shape (32,)
c = W.conj().T @ x                                     # step 1: c[m] = <w_m, x>, shape (32,) complex
x_back = (W @ c).real                                  # step 2: sum_m c[m] w_m
np.allclose(x, x_back), np.allclose((np.abs(x)**2).sum(), (np.abs(c)**2).sum())  # True, True
# the same c, fast: np.fft.fft(x, norm="ortho")
An orthonormal basis y(0), y(1) is given. How do you find the coefficient of y(1) for a signal x?

Chapter 11

Field Guide: The Lecture on One Page

Keep the numbers, the terms, the checklist and the core code, and see where this lecture feeds the rest of the course

A computer holds a signal as a list of numbers. Two choices build the list: how often to measure, which is sampling, and how finely to round, which is quantization. Sample below twice the highest frequency and fast waves wear slow masks, which is aliasing. Round too coarsely and noise grows by a known amount, 6 dB for every bit lost. Once you have the list, treat it as a point: it has a length, angles to other signals, and many possible descriptions, called bases. An orthonormal basis, above all the Fourier basis of pure tones, gives each coordinate with one inner product.

Numbers and terms

TermWhat it meansFormula or number
Discrete signalOne value per whole-number indexx[n] : ℤ → ℂ or ℝ
Digital signalWhole-number index and whole-number valuexdig[n] : ℤ → ℤ
Quantization levelsAllowed values with b bits2b; 8 bits = 256
Step sizeGap between levels on a range of width 2Δ = 2 / 2b; error at most Δ/2
Quantization SNRFull-scale sine over rounding noise6.02 b + 1.76 dB: 8 bits 49.9, 16 bits 98.1, 24 bits 146.2
Delta and siftingAny signal is a sum of shifted spikesx[n] = ∑ x[k] δ[n − k]
DecayEach sample a fixed fraction of the lastanu[n]; energy 1/(1 − |a|²)
SinusoidA point stepping around the circleA cos(ω0n + φ); f = ω0/2π cycles per sample
PeriodicityWhen a discrete sinusoid repeatsω0 = (M/N)π; period N if M even, 2N if M odd (lowest terms)
SamplingReading every T secondsx[n] = xa(nT); ω0 = 2πf0/fs
Nyquist-ShannonRate that keeps a band-limited wavefs > 2B; CD: 44,100 Hz for a 20,000 Hz band
AliasingWhere a fast tone appears|f0 − fs round(f0/fs)|; 7,000 Hz at 10,000 Hz shows as 3,000
Energy and powerTotal and average squared sizeE = ∑|x[n]|²; P = lim (1/(2N+1)) ∑|x[n]|²
Inner product, normAlikeness and length⟨x, y⟩ = ∑ xk* yk; ‖x‖ = √⟨x, x⟩
Cauchy-SchwarzInner product is bounded by the lengths|⟨x, y⟩| ≤ ‖x‖‖y‖
Basis and coefficientsN independent signals; weights that rebuild xx = ∑ c[k] y(k)
Orthonormal change of basisOne inner product per coefficient; energy keptc[k] = ⟨y(k), x⟩
Fourier basisN pure tones, m turns per windowwm[n] = ej2πnm/N / √N

Checklist before you trust a list of numbers

  1. Name the sampling period. A list without T has no frequencies in hertz.
  2. Find the highest frequency you care about, then check that the sample rate is above twice that.
  3. Filter before you sample or shrink. Aliasing cannot be undone afterwards.
  4. Count the levels your signal really uses. A quiet signal wastes bits and loses 20 dB for every factor of ten in loudness.
  5. Compare with angles, not raw inner products. Divide by the norms.
  6. Pick the basis that makes your signals sparse. Tones for waves, spikes for clicks.

The core, as code

pythonimport numpy as np
fs, f0, bits = 8000, 1000, 8
n = np.arange(64)
x = np.cos(2*np.pi*f0*n/fs)                           # sample: x[n] = xa(nT), shape (64,)
levels, d = 2**bits, 2/2**bits
q = (np.floor((x + 1)/d).clip(0, levels - 1) + 0.5)*d - 1   # quantize to 256 levels
snr_db = 10*np.log10(np.sum(x**2)/np.sum((q - x)**2)) # 48.2 here; formula 6.02*bits + 1.76 = 49.9
f_app = abs(f0 - fs*round(f0/fs))                     # apparent frequency: 1000 Hz, below fs/2 = 4000
energy = np.sum(np.abs(x)**2); power = energy/len(x)  # 32.0 and 0.5
c = np.fft.fft(x, norm="ortho")                       # coefficients in the Fourier basis, shape (64,)
assert np.allclose(energy, np.sum(np.abs(c)**2))      # the energy is the same in both bases

Where this sits in the course

The lecture cites four sources: Signal Processing for Communications by Prandoni and Vetterli, Digital Image Processing by Gonzalez and Woods, Pattern Recognition and Machine Learning by Bishop, and the EECS 351 lecture notes of Laura Balzano at the University of Michigan. Everything ahead uses this chapter’s tools. Quantization gets three lectures. The Fourier basis becomes the DFT. Inner products and norms return in every classifier from Lecture 9 on.

Keep going

The takeaway. A signal is a list, a list is a point, and every question about the signal becomes a question about the point: how far, how alike, in which directions. Sampling and quantization decide whether the list is faithful. The basis decides whether the list is useful.

Credit: this lesson re-teaches Lecture 2 of Stanford EE269 in our own words and devices. The course, its slides and its ideas belong to Mert Pilanci and the course team. Lecture 2 slides, all slides.

Now press Present or Teach and explain from memory why a 7,000 Hz whistle shows up at 3,000 Hz in a 10,000 Hz recording, and why a change of orthonormal basis keeps the energy. Then go back to the instrument at the top, drag Samples to 9, and say which tone is the impostor and why.

A voice recording sounds grainy and also holds a whistling tone that nobody played. Which pair of fixes matches the two faults?
EE269 Lecture 2: Discrete Signals
The course site · Lecture slides · All EE269 slides · Back to Gleams