Now that you’ve looked more closely at the process of sampling and quantization in this chapter, you should have a clearer understanding of the MATLAB and C++ examples in Chapters 2 and 3.
[aside]An alternative way to get the points at which samples are taken is this:
f = 440; sr = 44100; s = 1; t = [1:sr*s]; y = sin(2*pi*f*(t/sr*s));
Plugging in the numbers from this example, you get
y = sin(2*pi*440*t/44100);
[/aside]
In MATLAB, you can generate samples from a sine wave of frequency f at a sampling rate r for s seconds in the following way:
f = 440; sr = 44100; s = 1; t = linspace(0,s,sr * s); y = sin(2*pi*f*t);
We’ve looked at statements like these in Chapter 2, but let’s review. The statement linspace(0, s, sr * s) creates a one-dimensional array (which can also be called a vector) of sr*s values evenly spaced between 0 and s. These are the points at which the samples are to be taken. One statement in MATLAB can cause an operation to be done on every element of a vector. For example, y = sin(2*pi*f*t) takes the sine on each element of t and stores the result in vector y. Since t has 44100 values in it, y does also. In this way, MATLAB simulates the sampling process for a single-frequency sound wave.
[wpfilebase tag=file id=63 tpl=supplement /]
Quantization can also be simulated in MATLAB. Notice that from the above sequence of commands, all the elements of y are between -1 and 1. To quantize these values to a bit depth of b, you can do the following:
b = 8; sample_max = 2^(b-1)-1; y_quantized = floor(y*sample_max);
The plot function graphs the result.
plot(t, y);
If we want to zoom in on the first, say, 500 values, we can do so with
plot(t(1:500), y(1:500));
With these basic commands, you can do the suggested exercise linked with this section, which has you experiment with quantization error and dynamic range at various bit depths.