spectral entropy frequency bands in matlab

main.m
% Generate a sample signal
fs = 1000; % Sampling frequency
t = 0:1/fs:1-1/fs; % Time vector
A = [1, 2, 3]; % Amplitudes of the three frequency components
f = [5, 10, 15]; % Frequencies of the three frequency components
sig = A(1)*sin(2*pi*f(1)*t) + A(2)*sin(2*pi*f(2)*t) + A(3)*sin(2*pi*f(3)*t); % Signal

% Compute the power spectral density
p = pwelch(sig,[],[],[],fs); % Power spectral density
pnorm = p/sum(p); % Normalize to make it a pdf

% Calculate spectral entropy
entropy = -sum(pnorm.*log2(pnorm)); % Spectral entropy

% If you want to calculate the spectral entropy within specific frequency bands
band1 = [5, 7]; % Define Frequency band 1 (e.g., 5-7 Hz)
band2 = [8, 12]; % Define Frequency band 2 (e.g., 8-12 Hz)
band3 = [13, 20]; % Define Frequency band 3 (e.g., 13-20 Hz)

% Calculate the sub-entropy within each frequency band
idx1 = find(f >= band1(1) & f <= band1(2));
pnorm_band1 = pnorm(idx1)/sum(pnorm(idx1)); % Normalize for this band
entropy_band1 = -sum(pnorm_band1.*log2(pnorm_band1)); % Spectral entropy of band 1

idx2 = find(f >= band2(1) & f <= band2(2));
pnorm_band2 = pnorm(idx2)/sum(pnorm(idx2)); % Normalize for this band
entropy_band2 = -sum(pnorm_band2.*log2(pnorm_band2)); % Spectral entropy of band 2

idx3 = find(f >= band3(1) & f <= band3(2));
pnorm_band3 = pnorm(idx3)/sum(pnorm(idx3)); % Normalize for this band
entropy_band3 = -sum(pnorm_band3.*log2(pnorm_band3)); % Spectral entropy of band 3
1436 chars
32 lines

gistlibby LogSnag