费话不多,直接上代码
代码运行环境Matlab 2013B + eeglab13
% Spectral_EEG
clear all; clc;
Fs=1000; %% sampling rate
L=1000; %% signal length for FFT
T=1/Fs;
t=(0:L-1)*T;
NFFT=2^nextpow2(L);
f=Fs/2*linspace(0,1,NFFT/2+1);
f_idx=find(f<=30); %% region of interest
Subj=1:10;
for i=1:length(Subj)
setname=strcat(num2str(i),'_LH.set');
setpath='C:\Users\think\Desktop\test_data2\';
EEG = pop_loadset('filename',setname,'filepath',setpath);
for ii=1:size(EEG.data,1) %% channel
for jj=1:size(EEG.data,3) %% trial
x=squeeze(EEG.data(ii,1:1000,jj)); %% 1*1000
temp=fft(x,NFFT)/L;
Y(jj,:)=2*abs(temp(1:NFFT/2+1)); % fft results, in amplitude
Y_PSD(jj,:)=2*(abs(temp(1:NFFT/2+1))).^2; % fft results, in power
end
FFT_amplitude(i,ii,:)=squeeze(mean(Y(:,f_idx),1));clear Y;
FFT_power(i,ii,:)=squeeze(mean(Y_PSD(:,f_idx),1));clear Y;
end
end
%%% spectral amplitude
f_plot=f(f_idx);
figure; hold on;
plot(f_plot,squeeze(mean(FFT_amplitude(:,4,:),1)),'b','linewidth', 1.5);
plot(f_plot,squeeze(mean(FFT_amplitude(:,13,:),1)),'r','linewidth', 1.5);
plot(f_plot,squeeze(mean(FFT_amplitude(:,29,:),1)),'g','linewidth', 1.5);
axis([0 30 0 5]);
legend('Fz','Cz','Pz');
title('Group level FFT','fontsize',16);
xlabel('Frequency','fontsize',16);
ylabel('Spectral Amplitude (\muV)','fontsize',16);
delta_idx=find((f_plot>=1)&(f_plot<=3));
alpha_idx=find((f_plot>=8)&(f_plot<=12));
delta_mag=squeeze(mean(FFT_amplitude(:,:,delta_idx),3));
alpha_mag=squeeze(mean(FFT_amplitude(:,:,alpha_idx),3));
figure;
subplot(121); topoplot(mean(delta_mag,1),EEG.chanlocs,'maplimits',[-4 4]); title('delta','fontsize',16);
subplot(122); topoplot(mean(alpha_mag,1),EEG.chanlocs,'maplimits',[-3 3]); title('alpha','fontsize',16);
%%% spectral power
figure; hold on;
plot(f_plot,10*log10(squeeze(mean(FFT_power(:,4,:),1))),'b','linewidth', 1.5);
plot(f_plot,10*log10(squeeze(mean(FFT_power(:,13,:),1))),'r','linewidth', 1.5);
plot(f_plot,10*log10(squeeze(mean(FFT_power(:,29,:),1))),'g','linewidth', 1.5);
axis([0 30 -20 10]);
legend('Fz','Cz','Pz');
title('Group level FFT','fontsize',16);
xlabel('Frequency','fontsize',16);
ylabel('Spectral Power (dB)','fontsize',16);
delta_idx=find((f_plot>=1)&(f_plot<=3));
alpha_idx=find((f_plot>=8)&(f_plot<=12));
delta_mag=squeeze(mean(FFT_power(:,:,delta_idx),3));
alpha_mag=squeeze(mean(FFT_power(:,:,alpha_idx),3));
figure;
subplot(121); topoplot(mean(delta_mag,1),EEG.chanlocs,'maplimits',[-10 10]); title('delta','fontsize',16);
subplot(122); topoplot(mean(alpha_mag,1),EEG.chanlocs,'maplimits',[-10 10]); title('alpha','fontsize',16);