% Generate a sample signalfs = 1000; % Sampling frequencyt = 0:1/fs:1-1/fs; % Time vectorA = [1, 2, 3]; % Amplitudes of the three frequency componentsf = [5, 10, 15]; % Frequencies of the three frequency componentssig = 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 densityp = pwelch(sig,[],[],[],fs); % Power spectral densitypnorm = p/sum(p); % Normalize to make it a pdf% Calculate spectral entropyentropy = -sum(pnorm.*log2(pnorm)); % Spectral entropy% If you want to calculate the spectral entropy within specific frequency bandsband1 = [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 bandidx1 = find(f >= band1(1) & f <= band1(2));
pnorm_band1 = pnorm(idx1)/sum(pnorm(idx1)); % Normalize for this bandentropy_band1 = -sum(pnorm_band1.*log2(pnorm_band1)); % Spectral entropy of band 1idx2 = find(f >= band2(1) & f <= band2(2));
pnorm_band2 = pnorm(idx2)/sum(pnorm(idx2)); % Normalize for this bandentropy_band2 = -sum(pnorm_band2.*log2(pnorm_band2)); % Spectral entropy of band 2idx3 = find(f >= band3(1) & f <= band3(2));
pnorm_band3 = pnorm(idx3)/sum(pnorm(idx3)); % Normalize for this bandentropy_band3 = -sum(pnorm_band3.*log2(pnorm_band3)); % Spectral entropy of band 3