analyse_12_preprocess_pictureword_response.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. %% Setup
  2. % paths to data
  3. eeg_path = fullfile('raw_data', 'eeg-pc', 'pictureword');
  4. beh_path = fullfile('raw_data', 'stim-pc', 'data', 'pictureword');
  5. % import eeglab (assumes eeglab has been added to path), e.g.
  6. addpath('C:/EEGLAB/eeglab2020_0')
  7. [ALLEEG, EEG, CURRENTSET, ALLCOM] = eeglab;
  8. % This script uses fastica algorithm for ICA, so FastICA needs to be on the path, e.g.
  9. addpath('C:/EEGLAB/FastICA_25')
  10. % region of interest for trial-level ROI average
  11. roi = {'TP7', 'CP5', 'P7', 'P5', 'P9', 'PO7', 'PO3', 'O1'};
  12. % cutoff probability for identifying eye and muscle related ICA components with ICLabel
  13. icl_cutoff = 0.85;
  14. % sigma parameter for ASR
  15. asr_sigma = 20;
  16. %% Clear output folders
  17. delete(fullfile('sample_data_response', '*.csv'))
  18. %% Import lab book
  19. % handle commas in vectors
  20. lab_book_file = fullfile('raw_data', 'stim-pc', 'participants.csv');
  21. lab_book_raw_dat = fileread(lab_book_file);
  22. [regstart, regend] = regexp(lab_book_raw_dat, '\[.*?\]');
  23. for regmatch_i = 1:numel(regstart)
  24. str_i = lab_book_raw_dat(regstart(regmatch_i):regend(regmatch_i));
  25. str_i(str_i==',') = '.';
  26. lab_book_raw_dat(regstart(regmatch_i):regend(regmatch_i)) = str_i;
  27. end
  28. lab_book_fixed_file = fullfile('raw_data', 'stim-pc', 'participants_tmp.csv');
  29. lab_book_fixed_conn = fopen(lab_book_fixed_file, 'w');
  30. fprintf(lab_book_fixed_conn, lab_book_raw_dat);
  31. fclose(lab_book_fixed_conn);
  32. lab_book_readopts = detectImportOptions(lab_book_fixed_file, 'VariableNamesLine', 1, 'Delimiter', ',');
  33. % read subject ids as class character
  34. lab_book_readopts.VariableTypes{strcmp(lab_book_readopts.SelectedVariableNames, 'subj_id')} = 'char';
  35. lab_book = readtable(lab_book_fixed_file, lab_book_readopts);
  36. delete(lab_book_fixed_file)
  37. %% Count the total number of excluded electrodes
  38. n_bads = 0;
  39. n_bads_per_s = zeros(size(lab_book, 1), 0);
  40. for subject_nr = 1:size(lab_book, 1)
  41. bad_channels = eval(strrep(strrep(strrep(lab_book.pw_bad_channels{subject_nr}, '[', '{'), ']', '}'), '.', ','));
  42. n_bads_per_s(subject_nr) = numel(bad_channels);
  43. n_bads = n_bads + numel(bad_channels);
  44. end
  45. perc_bads = n_bads / (64 * size(lab_book, 1)) * 100;
  46. %% Import max electrode info
  47. % this contains participants' maximal electrodes for the N170 from the
  48. % localisation task
  49. max_elecs = readtable('max_elecs.csv');
  50. %% Iterate over subjects
  51. % record trial exclusions
  52. total_excl_trials_incorr = zeros(1, size(lab_book, 1));
  53. total_excl_trials_rt = zeros(1, size(lab_book, 1));
  54. n_bad_ica = zeros(size(lab_book, 1), 0);
  55. for subject_nr = 1:size(lab_book, 1)
  56. subject_id = lab_book.subj_id{subject_nr};
  57. fprintf('\n\n Subject Iteration %g/%g, ID: %s\n', subject_nr, size(lab_book, 1), subject_id)
  58. %% get subject-specific info from lab book
  59. exclude = lab_book.exclude(subject_nr);
  60. bad_channels = eval(strrep(strrep(strrep(lab_book.pw_bad_channels{subject_nr}, '[', '{'), ']', '}'), '.', ','));
  61. bad_trigger_indices = eval(strrep(lab_book.pw_bad_trigger_indices{subject_nr}, '.', ','));
  62. % add PO4 to bad channels, which seems to be consistently noisy, even when not marked as bad
  63. if sum(strcmp('PO4', bad_channels))==0
  64. bad_channels(numel(bad_channels)+1) = {'PO4'};
  65. end
  66. %% abort if excluded
  67. if exclude
  68. fprintf('Subject %s excluded. Preprocessing aborted.\n', subject_id)
  69. fprintf('Lab book note: %s\n', lab_book.note{subject_nr})
  70. continue
  71. end
  72. %% load participant's data
  73. % load raw eeg
  74. raw_datapath = fullfile(eeg_path, append(subject_id, '.bdf'));
  75. % abort if no EEG data collected yet
  76. if ~isfile(raw_datapath)
  77. fprintf('Subject %s skipped: no EEG data found\n', subject_id)
  78. continue
  79. end
  80. EEG = pop_biosig(raw_datapath, 'importevent', 'on', 'rmeventchan', 'off');
  81. % load behavioural
  82. all_beh_files = dir(beh_path);
  83. beh_regex_matches = regexpi({all_beh_files.name}, append('^', subject_id, '_.+\.csv$'), 'match');
  84. regex_emptymask = cellfun('isempty', beh_regex_matches);
  85. beh_regex_matches(regex_emptymask) = [];
  86. subj_beh_files = cellfun(@(x) x{:}, beh_regex_matches, 'UniformOutput', false);
  87. if size(subj_beh_files)>1
  88. fprintf('%g behavioural files found?\n', size(subj_beh_files))
  89. break
  90. end
  91. beh_datapath = fullfile(beh_path, subj_beh_files{1});
  92. beh = readtable(beh_datapath);
  93. %% Set data features
  94. % set channel locations
  95. orig_locs = EEG.chanlocs;
  96. EEG.chanlocs = pop_chanedit(EEG.chanlocs, 'load', {'BioSemi64.loc', 'filetype', 'loc'}); % doesn't match order for the data
  97. % set channel types
  98. for ch_nr = 1:64
  99. EEG.chanlocs(ch_nr).type = 'EEG';
  100. end
  101. for ch_nr = 65:72
  102. EEG.chanlocs(ch_nr).type = 'EOG';
  103. end
  104. for ch_nr = 73:79
  105. EEG.chanlocs(ch_nr).type = 'MISC';
  106. end
  107. for ch_nr = 65:79
  108. EEG.chanlocs(ch_nr).theta = [];
  109. EEG.chanlocs(ch_nr).radius = [];
  110. EEG.chanlocs(ch_nr).sph_theta = [];
  111. EEG.chanlocs(ch_nr).sph_phi = [];
  112. EEG.chanlocs(ch_nr).X = [];
  113. EEG.chanlocs(ch_nr).Y = [];
  114. EEG.chanlocs(ch_nr).Z = [];
  115. end
  116. % change the order of channels in EEG.data to match the new order in chanlocs
  117. data_reordered = EEG.data;
  118. for ch_nr = 1:64
  119. % make sure the new eeg data array matches the listed order
  120. ch_lab = EEG.chanlocs(ch_nr).labels;
  121. orig_locs_idx = find(strcmp(lower({orig_locs.labels}), lower(ch_lab)));
  122. data_reordered(ch_nr, :) = EEG.data(orig_locs_idx, :);
  123. end
  124. EEG.data = data_reordered;
  125. % remove unused channels
  126. EEG = pop_select(EEG, 'nochannel', 69:79);
  127. % remove bad channels
  128. ur_chanlocs = EEG.chanlocs; % store a copy of the full channel locations before removing (for later interpolation)
  129. bad_channels_indices = find(ismember(lower({EEG.chanlocs.labels}), lower(bad_channels)));
  130. EEG = pop_select(EEG, 'nochannel', bad_channels_indices);
  131. %% Identify events (trials) - getting the response as the trigger instead of the word
  132. % make the sopen function happy
  133. x = fileparts( which('sopen') );
  134. rmpath(x);
  135. addpath(x,'-begin');
  136. % build the events manually from the raw eeg file (pop_biosig removes event offsets)
  137. % NB: this assumes no resampling between reading the BDF file and now
  138. bdf_dat = sopen(raw_datapath, 'r', [0, Inf], 'OVERFLOWDETECTION:OFF');
  139. event_types = bdf_dat.BDF.Trigger.TYP;
  140. event_pos = bdf_dat.BDF.Trigger.POS;
  141. event_time = EEG.times(event_pos);
  142. sclose(bdf_dat);
  143. clear bdf_dat;
  144. triggers = struct(...
  145. 'off', 0,...
  146. 'A1', 1,...
  147. 'A2', 2,...
  148. 'practice', 25,...
  149. 'image', 99);
  150. % add 61440 to each trigger value (because of number of bits in pp)
  151. trigger_labels = fieldnames(triggers);
  152. for field_nr = 1:numel(trigger_labels)
  153. triggers.(trigger_labels{field_nr}) = triggers.(trigger_labels{field_nr}) + 61440;
  154. end
  155. % remove the first trigger if it is at time 0 and has a value which isn't a recognised trigger
  156. if (event_time(1)==0 && ~ismember(event_types(1), [triggers.off, triggers.A1, triggers.A2, triggers.practice, triggers.image]))
  157. event_types(1) = [];
  158. event_pos(1) = [];
  159. event_time(1) = [];
  160. end
  161. % remove the new first trigger if it has a value of off
  162. if (event_types(1)==triggers.off)
  163. event_types(1) = [];
  164. event_pos(1) = [];
  165. event_time(1) = [];
  166. end
  167. % check every second trigger is an offset
  168. offset_locs = find(event_types==triggers.off);
  169. if any(offset_locs' ~= 2:2:numel(event_types))
  170. fprintf('Expected each second trigger to be an off?')
  171. break
  172. end
  173. % check every first trigger is non-zero
  174. onset_locs = find(event_types~=triggers.off);
  175. if any(onset_locs' ~= 1:2:numel(event_types))
  176. fprintf('Expected each first trigger to be an event?')
  177. break
  178. end
  179. % create the events struct manually
  180. events_onset_types = event_types(onset_locs);
  181. % events_onsets = event_pos(onset_locs);
  182. events_offsets = event_pos(offset_locs);
  183. % events_durations = events_offsets - events_onsets;
  184. % adjust manually so that we timelock to responses
  185. events_onsets = events_offsets;
  186. events_offsets = events_onsets + 500 * 1000/EEG.srate;
  187. events_durations = events_offsets - events_onsets;
  188. EEG.event = struct();
  189. for event_nr = 1:numel(events_onsets)
  190. EEG.event(event_nr).type = events_onset_types(event_nr);
  191. EEG.event(event_nr).latency = events_onsets(event_nr);
  192. EEG.event(event_nr).offset = events_offsets(event_nr);
  193. EEG.event(event_nr).duration = events_durations(event_nr);
  194. end
  195. % copy the details over to urevent
  196. EEG.urevent = EEG.event;
  197. % record the urevent
  198. for event_nr = 1:numel(events_onsets)
  199. EEG.event(event_nr).urevent = event_nr;
  200. end
  201. % remove bad events recorded in lab book (misfired triggers)
  202. EEG = pop_editeventvals(EEG, 'delete', find(ismember([EEG.event.urevent], bad_trigger_indices)));
  203. % remove practice trials
  204. EEG = pop_editeventvals(EEG, 'delete', find(ismember([EEG.event.type], triggers.practice)));
  205. % remove triggers saying that image is displayed
  206. EEG = pop_editeventvals(EEG, 'delete', find(ismember([EEG.event.type], triggers.image)));
  207. % check the events make sense
  208. if sum(~ismember([EEG.event.type], [triggers.A1, triggers.A2])) > 0
  209. fprintf('Unexpected trial types?\n')
  210. break
  211. end
  212. if numel({EEG.event.type})~=200
  213. fprintf('%g trial triggers detected?\n', numel({EEG.event.type}))
  214. break
  215. end
  216. if sum(ismember([EEG.event.type], [triggers.A1])) ~= sum(ismember([EEG.event.type], [triggers.A2]))
  217. fprintf('Unequal number of congruent and incongruent trials?\n')
  218. break
  219. end
  220. % add the trials' onsets, offsets, durations, and triggers to the behavioural data
  221. beh.event = zeros(size(beh, 1), 1);
  222. beh.latency = zeros(size(beh, 1), 1);
  223. for row_nr = 1:size(beh, 1)
  224. cond_i = beh.condition(row_nr);
  225. beh.event(row_nr) = triggers.(cond_i{:});
  226. beh.latency(row_nr) = EEG.event(row_nr).latency;
  227. beh.offset(row_nr) = EEG.event(row_nr).offset;
  228. beh.duration(row_nr) = EEG.event(row_nr).duration;
  229. beh.duration_ms(row_nr) = (EEG.event(row_nr).duration * 1000/EEG.srate) - 500; % minus 500 as event timer starts at word presentation, but rt timer starts once word turns green
  230. end
  231. % check events expected in beh are same as those in the events struct
  232. if any(beh.event' ~= [EEG.event.type])
  233. fprintf('%g mismatches between behavioural data and triggers?\n', sum(beh.event' ~= [EEG.event.type]))
  234. break
  235. end
  236. % record trial numbers in EEG.event
  237. for row_nr = 1:size(beh, 1)
  238. EEG.event(row_nr).trl_nr = beh.trl_nr(row_nr);
  239. end
  240. %% Remove segments of data that fall outside of blocks
  241. % record block starts
  242. beh.is_block_start(1) = 1;
  243. for row_nr = 2:size(beh, 1)
  244. beh.is_block_start(row_nr) = beh.block_nr(row_nr) - beh.block_nr(row_nr-1) == 1;
  245. end
  246. % record block ends
  247. beh.is_block_end(size(beh, 1)) = 1;
  248. for row_nr = 1:(size(beh, 1)-1)
  249. beh.is_block_end(row_nr) = beh.block_nr(row_nr+1) - beh.block_nr(row_nr) == 1;
  250. end
  251. % record block boundaries (first start and last end point of each block, with 1 seconds buffer, or 1.5 seconds before)
  252. beh.block_boundary = zeros(size(beh, 1), 1);
  253. for row_nr = 1:size(beh, 1)
  254. if beh.is_block_start(row_nr)
  255. beh.block_boundary(row_nr) = beh.latency(row_nr) - (EEG.srate * 1.5);
  256. elseif beh.is_block_end(row_nr)
  257. beh.block_boundary(row_nr) = beh.offset(row_nr) + (EEG.srate * 1);
  258. end
  259. end
  260. % get the boundary indices in required format (start1, end1; start2, end2; start3, end3)
  261. block_boundaries = reshape(beh.block_boundary(beh.block_boundary~=0), 2, [])';
  262. % remove anything outside of blocks
  263. EEG = pop_select(EEG, 'time', (block_boundaries / EEG.srate));
  264. %% Trial selection
  265. % include only correct responses
  266. beh_filt_acc_only = beh(beh.acc==1, :);
  267. excl_trials_incorr = size(beh, 1)-size(beh_filt_acc_only, 1);
  268. total_excl_trials_incorr(subject_nr) = excl_trials_incorr;
  269. fprintf('Lost %g trials to incorrect responses\n', excl_trials_incorr)
  270. % include only responses between 100 and 1500 ms
  271. beh_filt = beh_filt_acc_only(beh_filt_acc_only.rt<=1500, :);
  272. excl_trials_rt = size(beh_filt_acc_only, 1)-size(beh_filt, 1);
  273. total_excl_trials_rt(subject_nr) = excl_trials_rt;
  274. fprintf('Lost %g trials to RTs above 1500\n', excl_trials_rt)
  275. fprintf('Lost %g trials in total to behavioural data\n', size(beh, 1)-size(beh_filt, 1))
  276. % filter the events structure
  277. discarded_trls = beh.trl_nr(~ismember(beh.trl_nr, beh_filt.trl_nr));
  278. discarded_events_indices = []; % (collect in a for loop, as [EEG.event.trl_nr] would remove missing data)
  279. for event_nr = 1:size(EEG.event, 2)
  280. if ismember(EEG.event(event_nr).trl_nr, discarded_trls)
  281. discarded_events_indices = [discarded_events_indices, event_nr];
  282. end
  283. end
  284. EEG = pop_editeventvals(EEG, 'delete', discarded_events_indices);
  285. % check the discarded trials are the expected length
  286. if numel(discarded_trls) ~= size(beh, 1)-size(beh_filt, 1)
  287. fprintf('Mismatch between behavioural data and EEG events in the number of trials to discard?')
  288. break
  289. end
  290. % check the sizes match
  291. if numel([EEG.event.trl_nr]) ~= size(beh_filt, 1)
  292. fprintf('Inconsistent numbers of trials between events structure and behavioural data after discarding trials?')
  293. break
  294. end
  295. % check the trl numbers match
  296. if any([EEG.event.trl_nr]' ~= beh_filt.trl_nr)
  297. fprintf('Trial IDs mmismatch between events structure and behavioural data after discarding trials?')
  298. break
  299. end
  300. %% Rereference, downsample, and filter
  301. % rereference
  302. EEG = pop_reref(EEG, []);
  303. % downsample
  304. EEG = pop_resample(EEG, 512);
  305. % filter
  306. % EEG = eeglab_butterworth(EEG, 0.5, 40, 4, 1:size(EEG.chanlocs, 2)); % preregistered filter
  307. EEG = eeglab_butterworth(EEG, 0.1, 40, 4, 1:size(EEG.chanlocs, 2)); % filter with lower highpass
  308. %% ICA
  309. % apply ASR
  310. %EEG_no_asr = EEG;
  311. %EEG = clean_asr(EEG, asr_sigma, [], [], [], [], [], [], [], [], 1024); % The last number is available memory in mb, needed for reproducibility
  312. % ASR is not used in this exploratory analysis
  313. rng(3101) % set seed for reproducibility
  314. EEG = pop_runica(EEG, 'icatype', 'fastica', 'approach', 'symm');
  315. % classify components with ICLabel
  316. EEG = iclabel(EEG);
  317. % store results for easy indexing
  318. icl_res = EEG.etc.ic_classification.ICLabel.classifications;
  319. icl_classes = EEG.etc.ic_classification.ICLabel.classes;
  320. % identify and remove artefact components
  321. artefact_comps = find(icl_res(:, strcmp(icl_classes, 'Eye')) >= icl_cutoff | icl_res(:, strcmp(icl_classes, 'Muscle')) >= icl_cutoff);
  322. fprintf('Removing %g artefact-related ICA components\n', numel(artefact_comps))
  323. n_bad_ica(subject_nr) = numel(artefact_comps);
  324. %EEG_no_iclabel = EEG;
  325. EEG = pop_subcomp(EEG, artefact_comps);
  326. %% Interpolate bad channels
  327. % give the original chanlocs structure so EEGLAB interpolates the missing electrode(s)
  328. if numel(bad_channels)>0
  329. EEG = pop_interp(EEG, ur_chanlocs);
  330. end
  331. %% Get sample level microvolts for exploratory analysis checking image ERPs
  332. disp('Getting sample-level results...')
  333. % resample to 256 Hz
  334. EEG_256 = pop_resample(EEG, 256);
  335. % get epochs of low-srate data
  336. EEG_epo_256 = pop_epoch(EEG_256, {triggers.A1, triggers.A2}, [-1, 0.5]);
  337. % remove baseline - don't do this for the response ERP at present
  338. % EEG_epo_256 = pop_rmbase(EEG_epo_256, [-200, 0]);
  339. % pre-allocate the table
  340. var_names = {'subj_id', 'stim_grp', 'resp_grp', 'item_nr', 'ch_name', 'time', 'uV'};
  341. var_types = {'string', 'string', 'string', 'double', 'string', 'double', 'double'};
  342. nrows = 64 * size(EEG_epo_256.times, 2) * size(beh_filt, 1);
  343. sample_res = table('Size',[nrows, numel(var_names)], 'VariableTypes',var_types, 'VariableNames',var_names);
  344. sample_res.subj_id = repmat(beh_filt.subj_id, 64*size(EEG_epo_256.times, 2), 1);
  345. sample_res.stim_grp = repmat(beh_filt.stim_grp, 64*size(EEG_epo_256.times, 2), 1);
  346. sample_res.resp_grp = repmat(beh_filt.resp_grp, 64*size(EEG_epo_256.times, 2), 1);
  347. % get the 64 channel eeg data as an array
  348. eeg_arr = EEG_epo_256.data(1:64, :, :);
  349. % a vector of all eeg data
  350. eeg_vec = squeeze(reshape(eeg_arr, 1, 1, []));
  351. % array and vector of the channel labels for each value in EEG.data
  352. channel_labels_arr = cell(size(eeg_arr));
  353. channel_label_lookup = {EEG_epo_256.chanlocs.labels};
  354. for chan_nr = 1:size(eeg_arr, 1)
  355. channel_labels_arr(chan_nr, :, :) = repmat(channel_label_lookup(chan_nr), size(channel_labels_arr, 2), size(channel_labels_arr, 3));
  356. end
  357. channel_labels_vec = squeeze(reshape(channel_labels_arr, 1, 1, []));
  358. % array and vector of the item numbers for each value in EEG.data
  359. times_arr = zeros(size(eeg_arr));
  360. times_lookup = EEG_epo_256.times;
  361. for time_idx = 1:size(eeg_arr, 2)
  362. times_arr(:, time_idx, :) = repmat(times_lookup(time_idx), size(times_arr, 1), size(times_arr, 3));
  363. end
  364. times_vec = squeeze(reshape(times_arr, 1, 1, []));
  365. % array and vector of the trial numbers
  366. trials_arr = zeros(size(eeg_arr));
  367. trials_lookup = beh_filt.item_nr;
  368. for trl_idx = 1:size(eeg_arr, 3)
  369. trials_arr(:, :, trl_idx) = repmat(trials_lookup(trl_idx), size(trials_arr, 1), size(trials_arr, 2));
  370. end
  371. trials_vec = squeeze(reshape(trials_arr, 1, 1, []));
  372. % store sample-level results in the table
  373. sample_res.ch_name = channel_labels_vec;
  374. sample_res.item_nr = trials_vec;
  375. sample_res.time = times_vec;
  376. sample_res.uV = eeg_vec;
  377. % look up and store some info about the trials
  378. trial_info_lookup = beh_filt(:, {'item_nr', 'condition', 'image', 'string'});
  379. sample_res = outerjoin(sample_res, trial_info_lookup, 'MergeKeys', true);
  380. % sort by time, channel, item_nr
  381. sample_res = sortrows(sample_res, {'time', 'ch_name', 'item_nr'});
  382. %% save the results
  383. disp('Saving results...')
  384. writetable(sample_res, fullfile('sample_data_response', [subject_id, '.csv']));
  385. end
  386. fprintf('\nFinished preprocessing picture-word data!\n')
  387. %% Functions
  388. % custom function for applying a Butterworth filter to EEGLAB data
  389. function EEG = eeglab_butterworth(EEG, low, high, order, chanind)
  390. fprintf('Applying Butterworth filter between %g and %g Hz (order of %g)\n', low, high, order)
  391. % create filter
  392. [b, a] = butter(order, [low, high]/(EEG.srate/2));
  393. % apply to data (requires transposition for filtfilt)
  394. data_trans = single(filtfilt(b, a, double(EEG.data(chanind, :)')));
  395. EEG.data(chanind, :) = data_trans';
  396. end
  397. % custom function for finding the closest timepoint in an EEG dataset
  398. function [idx, closesttime] = eeglab_closest_time(EEG, time)
  399. dists = abs(EEG.times - time);
  400. idx = find(dists == min(dists));
  401. % in the unlikely case there are two equidistant times, select one randomly
  402. if numel(idx) > 1
  403. fprintf('Two equidistant times! Selecting one randomly.')
  404. idx = idx(randperm(numel(idx)));
  405. idx = idx(1);
  406. end
  407. closesttime = EEG.times(idx);
  408. end