Digital Sound & Music: Concepts, Applications, & Science, Chapter 5, last updated 6/25/2013
5.3.5 Simulating Sampling and Quantization in MATLAB
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
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.
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.
5.3.6 Simulating Sampling and Quantization in C++
You can simulate sampling and quantization in C++ just as you can in MATLAB. The
difference is that you need loops to operate on arrays in C++, while one command in MATLAB
can cause an operation to be performed on each element in an array. (You can also write loops
in MATLAB, but it isn't necessary where array operations are available.) For example, the
equivalent of the MATLAB lines above is given in C++ below. (We use mostly C syntax but,
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);
Previous Page Next Page