Certainly! Here's a MATLAB Live Script that demonstrates the concept of frequency bins using a simple example. You can copy and paste this code into a new MATLAB Live Script or modify it as needed.
Frequency Bins in MATLAB
In this example, we will create a signal, compute its Fourier transform using the Fast Fourier Transform (FFT), and visualize the frequency bins.
Step 1: Create a Signal
We'll generate a simple sine wave with two frequencies: 10 Hz and 30 Hz.
Fs = 1000; % Sampling frequency (Hz)
t = 0:1/Fs:1-1/Fs; % Time vector (1 second)
f1 = 10; % Frequency 1 (Hz)
f2 = 30; % Frequency 2 (Hz)
signal = sin(2*pi*f1*t) + sin(2*pi*f2*t); % Signal with two frequencies
Step 2: Compute FFT
Now, we'll compute the FFT of the signal and determine the frequency bins.
N = length(signal); % Number of samples
Y = fft(signal); % FFT of the signal
frequencies = (0:N-1)*(Fs/N); % Frequency vector (Hz)
Step 3: Visualize the FFT and Frequency Bins
To understand frequency bins, we'll plot the magnitude of the FFT and highlight the frequency bins corresponding to our two frequencies.
figure;
plot(frequencies, abs(Y), 'LineWidth', 1.5);
xlim([0 Fs/2]);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Magnitude Spectrum (First Half)');
% Highlight the frequency bins for f1 and f2
bin1 = find(frequencies == f1, 1);
bin2 = find(frequencies == f2, 1);
hold on;
plot([frequencies(bin1) frequencies(bin1)], [0 max(abs(Y))], 'r--', 'LineWidth', 1.5);
plot([frequencies(bin2) frequencies(bin2)], [0 max(abs(Y))], 'g--', 'LineWidth', 1.5);
hold off;
This script generates a plot showing the magnitude of the FFT, with the frequency bins corresponding to 10 Hz and 30 Hz highlighted. Note that the frequency resolution is given by Fs/N, and the plot only shows the positive frequencies (up to Fs/2), as the FFT is symmetric.
In this example, you can see how the FFT divides the frequency spectrum into bins, and how each bin corresponds to a specific frequency. The width of each bin depends on the sampling frequency and the number of samples.