eeg_autocorr_welch.m 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. function ac = eeg_autocorr_welch(EEG, pct_data)
  2. % clean input cutoff freq
  3. if ~exist('pct_data', 'var') || isempty(pct_data)
  4. pct_data = 100;
  5. end
  6. % setup constants
  7. ncomp = size(EEG.icaweights, 1);
  8. n_points = min(EEG.pnts, EEG.srate * 3);
  9. nfft = 2^nextpow2(n_points * 2 - 1);
  10. cutoff = floor(EEG.pnts / n_points) * n_points;
  11. index = bsxfun(@plus, ceil(0:n_points / 2:cutoff - n_points), (1:n_points)');
  12. % separate data segments
  13. if pct_data ~=100
  14. rng(0)
  15. n_seg = size(index, 2) * EEG.trials;
  16. subset = randperm(n_seg, ceil(n_seg * pct_data / 100)); % need to find a better way to take subset
  17. rng('shuffle') % remove duplicate data first (from 50% overlap)
  18. temp = reshape(EEG.icaact(:, index, :), [ncomp size(index) .* [1 EEG.trials]]);
  19. segments = temp(:, :, subset);
  20. else
  21. segments = reshape(EEG.icaact(:, index, :), [ncomp size(index) .* [1 EEG.trials]]);
  22. end
  23. %% calc autocorrelation
  24. fftpow = abs(fft(segments, nfft, 2)).^2;
  25. ac = ifft(mean(fftpow, 3), [], 2);
  26. % normalize
  27. if EEG.pnts < EEG.srate
  28. ac = [ac(:, 1:EEG.pnts, :) ./ (ac(:, 1) * (n_points:-1:1) / (n_points)) ...
  29. zeros(ncomp, EEG.srate - n_points + 1)];
  30. else
  31. ac = ac(:, 1:EEG.srate + 1, :) ./ ...
  32. (ac(:, 1) * [(n_points:-1:n_points - EEG.srate + 1) ...
  33. max(1, n_points - EEG.srate)] / (n_points));
  34. end
  35. % resample to 1 second at 100 samples/sec
  36. ac = resample(ac', 100, EEG.srate)';
  37. ac(:, 1) = [];