How do you implement DSP algorithms in MATLAB or Python?

ampheoampheo
3 min read

Implementing DSP (Digital Signal Processing) algorithms in MATLAB or Python involves using built-in libraries and signal processing toolkits to analyze, filter, transform, and synthesize signals.

Here's how to do it in both environments:


Common DSP Algorithms

  • FIR/IIR filtering

  • FFT and spectral analysis

  • Convolution and correlation

  • Signal generation and noise removal

  • Modulation/demodulation

  • Feature extraction (e.g., MFCC, envelope, RMS)


1. MATLAB Implementation

MATLAB is widely used in DSP due to its built-in functions and toolboxes.

Example: Low-pass FIR Filter

matlab

Fs = 1000;                 % Sampling frequency
t = 0:1/Fs:1;              % Time vector
x = sin(2*pi*50*t) + sin(2*pi*200*t); % Composite signal

% Design FIR low-pass filter
fc = 100;                  % Cutoff frequency
n = 50;                    % Filter order
b = fir1(n, fc/(Fs/2));    % Normalize frequency

% Apply filter
y = filter(b, 1, x);

% Plot
plot(t, x, 'b', t, y, 'r');
legend('Original', 'Filtered');

🛠 Useful MATLAB DSP Functions

TaskFunction
FFTfft, ifft
Filter design (FIR/IIR)fir1, butter
Filter applicationfilter, filtfilt
Spectrogramspectrogram
Convolutionconv

2. Python Implementation

Python uses libraries like NumPy, SciPy, Matplotlib, and scikit-dsp-comm or PyDSP.

Example: FIR Filter with SciPy

python

import numpy as np
from scipy.signal import firwin, lfilter
import matplotlib.pyplot as plt

Fs = 1000
t = np.linspace(0, 1, Fs, endpoint=False)
x = np.sin(2 * np.pi * 50 * t) + np.sin(2 * np.pi * 200 * t)

# Design FIR filter
fc = 100
numtaps = 51
b = firwin(numtaps, fc, fs=Fs)

# Apply filter
y = lfilter(b, 1.0, x)

# Plot
plt.plot(t, x, label='Original')
plt.plot(t, y, label='Filtered', color='red')
plt.legend()
plt.show()

Useful Python DSP Libraries

TaskLibraryFunction
FFTNumPy, SciPynp.fft.fft, scipy.fft
Filter designSciPyfirwin, butter, cheby1
Filter applicationSciPylfilter, filtfilt
Spectrogram / STFTSciPy, Librosaspectrogram, stft
Audio DSPLibrosaload, mfcc, resample

Choosing MATLAB vs Python

FeatureMATLABPython
Ease of useVery high (DSP toolbox)Moderate to high
CostProprietaryFree/open-source
Real-time DSP supportWith Simulink/ToolboxesLimited, but possible with sounddevice or PyAudio
EcosystemEngineering-heavyData science, ML, IoT friendly

Optional: Real-time DSP in Python

python

import sounddevice as sd

def callback(indata, outdata, frames, time, status):
    # Simple pass-through or filter processing
    outdata[:] = indata

with sd.Stream(callback=callback):
    sd.sleep(10000)  # Run for 10 seconds
0
Subscribe to my newsletter

Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ampheo
ampheo