Can somebody please tell me if the below code to calculate power spectral density is right or not? gmac’s code is used for calculating the magnitude, which is ‘spectrum’ here.
inputData=csvread(‘./EEG.csv’);
eeg.raw= inputData(:,(3:6));
fftlength = 256; % make the window for sample length fftlength, 2 seconds in this case
hanning = (1:fftlength)’;
hanning_in = 2* pi() * (hanning – (fftlength+1)/2)/(fftlength+1); %rescaled x-axis to match sample length
hanning = (sin(hanning_in)./hanning_in).^2; % sinc^2
hanning = repmat(hanning, 1, 4); % match to number of channels
f=(128/fftlength:128/fftlength:128); % frequency index for the spectral array
alphaIndex = find(f>=2 & f<=15);
totIndex = find(f>=1 & f<=60);
med = median(eeg.raw,2); % remove median of each sample
eeg.raw = eeg.raw – repmat(med, 1, 4);
for j=2:size(eeg.raw,1) % limit slew rate
del = eeg.raw(j,:) – eeg.raw(j-1,:);
del = min(del, ones(1,4)*5);
del = max(del, -ones(1,4)*5);
eeg.raw(j,:) = eeg.raw(j-1,:) + del;
end
% High pass filter
a = 0.0078125; % HPF filter coeffs
b = 0.9921875;
preVal = zeros(1,4);
eeg.filt = zeros(size(eeg.raw));
for j=2:size(eeg.raw,1)
preVal = a * eeg.raw(j,:) + b * preVal;
eeg.filt(j,:) = eeg.raw(j,:) – preVal;
end
% end HPF
eeg.alpha = [];
eeg.tot = [];
eeg.totmed = [];
for k = fftlength:32:size(eeg.filt,1) % step through every quarter second starting at first possible sample
spectrum = fft(eeg.filt(k-fftlength+1:k,:) .* hanning); % apply window to HP filtered data
spectrum = sqrt(spectrum .* conj(spectrum)); % get magnitude
eeg.alpha = [eeg.alpha; k sum(spectrum(alphaIndex,:))]; % append total spectral power in band, including sample index k
eeg.tot = [eeg.tot; k sum(spectrum(totIndex,:))];
end
% [Pxx,F] = periodogram(eeg.channelData,rectwin(length(eeg.channelData)),length(eeg.channelData),32);
data=sum(spectrum,2);
for p=1:length(data)
data(p)= data(p)/4;
end
freq=[1 15];
[Pxx,F] = periodogram(data,[],length(data),32);
Lw = 350; %window size
wa=hamming(Lw);
noverlap = 175; %according to the window size this is 50%
[PSD F]=pwelch(spectrum,[],noverlap,length(spectrum),32);
plot(F, 10*log10(PSD))
% xlabel(‘Frequency (Hz)’);
% ylabel(‘PSD’);