Certainly! Here's a MATLAB Live Script that demonstrates how to calculate and visualize frequency bins in a specific range.
matlab
% Define the signal parameters
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
% Create a signal with two frequencies
f1 = 50; % Frequency of the first component
f2 = 150; % Frequency of the second component
S = 0.7*sin(2*pi*f1*t) + sin(2*pi*f2*t); % Signal
% Plot the signal in the time domain
subplot(2,1,1);
plot(t, S);
title('Signal in the Time Domain');
xlabel('Time (s)');
ylabel('Amplitude');
% Perform FFT to get the frequency domain representation
Y = fft(S);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(L/2))/L;
% Define the frequency bins of interest
bin_start = 40;
bin_end = 160;
% Find the indices corresponding to the frequency bins
idx_start = find(f >= bin_start, 1);
idx_end = find(f <= bin_end, 1, 'last');
% Plot the FFT representation with frequency bins highlighted
subplot(2,1,2);
plot(f, P1);
hold on;
plot(f(idx_start:idx_end), P1(idx_start:idx_end), 'r', 'LineWidth', 2);
hold off;
title('Single-Sided Amplitude Spectrum of Signal');
xlabel('Frequency (Hz)');
ylabel('Amplitude');
grid on;
% Highlight the frequency bins
highlight = f(idx_start:idx_end);
text(highlight(1), max(P1), ['Bin Start: ' num2str(bin_start) ' Hz'], 'Color', 'r');
text(highlight(end), max(P1), ['Bin End: ' num2str(bin_end) ' Hz'], 'Color', 'r');
This MATLAB Live Script generates a signal with two frequencies and plots its time domain representation. It then calculates the FFT to obtain the frequency domain representation and highlights the frequency bins specified by the bin_start and bin_end variables. The highlighted frequency bins are also labeled on the plot for better visualization.
You can run this script in MATLAB Live Editor to see how frequency bins are calculated and visualized in the context of an FFT analysis.