DEV Community

Alain Ordoñez Alvaro
Alain Ordoñez Alvaro

Posted on

From Analog to Digital: Signal Simulation in MATLAB

When we deal with audio, sensors, or communication systems, most of the signals start as analog — continuous in time and amplitude. Computers, however, need digital signals. This post shows how to simulate the process of sampling and quantization in MATLAB, and how signal quality depends on these steps.

1. Analog Signal

We start with a simple sine wave at 100 Hz:

t = 0:0.0001:0.01;
f = 100;
x_analog = sin(2*pi*f*t);

plot(t, x_analog, 'k', 'LineWidth', 1.5);
title('Analog Signal');
Enter fullscreen mode Exit fullscreen mode

This represents a continuous-time signal.

2. Sampling (Nyquist Theorem)

The Nyquist theorem says we need to sample at least 2 × frequency to avoid aliasing. For a 100 Hz sine wave, that means ≥ 200 Hz.

We try three cases:

  • Below Nyquist: 150 Hz
  • At Nyquist: 200 Hz
  • Above Nyquist: 1000 Hz
Fs_list = [150, 200, 1000]; % Hz
colors = {'r', 'g', 'b'};

for i = 1:length(Fs_list)
    Fs = Fs_list(i);
    Ts = 1/Fs;
    n = 0:Ts:0.01;
    x_sampled = sin(2*pi*f*n);

    subplot(3,1,i);
    stem(n, x_sampled, colors{i}, 'filled');
    hold on;
    plot(t, x_analog, 'k');
    title(['Sampling at Fs = ' num2str(Fs) ' Hz']);
end

Enter fullscreen mode Exit fullscreen mode

👉 Result:

  • At 150 Hz, aliasing appears (signal looks distorted).
  • At 200 Hz, it’s just sufficient.
  • At 1000 Hz, the sampled signal closely follows the analog one.

3. Quantization

After sampling, amplitudes are still continuous. Quantization maps them to discrete levels. More levels = better quality, but more bits needed.

We try 8, 16, and 64 levels (3, 4, and 6 bits):

bits_list = [3, 4, 6]; % bits
Fs = 1000;             % high sampling to isolate quantization effect
Ts = 1/Fs;
n = 0:Ts:0.01;
x_sampled = sin(2*pi*f*n);

for j = 1:length(bits_list)
    bits = bits_list(j);
    levels = 2^bits;

    x_min = min(x_sampled);
    x_max = max(x_sampled);
    q_step = (x_max - x_min)/levels;

    x_index = round((x_sampled - x_min)/q_step);
    x_quantized = x_index*q_step + x_min;

    subplot(3,1,j);
    stem(n, x_quantized, 'filled');
    hold on;
    plot(t, x_analog, 'k');
    title([num2str(levels) ' Levels (' num2str(bits) ' bits)']);
end

Enter fullscreen mode Exit fullscreen mode

👉 Result:

  • With 8 levels, the signal looks blocky.
  • With 16 levels, smoother.
  • With 64 levels, almost identical to analog.

4. Conclusion

This small experiment shows the trade-offs in digital signal processing:

  • Sampling frequency determines whether aliasing occurs.
  • Quantization levels control resolution and quality.
  • More samples and more bits mean better accuracy, but also more storage and bandwidth.

👉 Code + plots are available here: https://github.com/alainord/Mathematical-Algorithms-1st-assigment#

Top comments (0)