function[obj] = label(obj, params) %% extract labels from all MSG events %% Step 1: read pattern from label_pattern (the varying part) for p = 1:length(obj.label_patterns) [token remainder] = strtok(obj.label_patterns{p},'%'); match{p} = strtrim(token); if isempty(match{p}) match{p} = strtrim(strtok(remainder)); end end %% allocate only MSG events msg_ind = regexp(obj.events_, 'MSG'); ind = find(~cellfun(@isempty,msg_ind)); l_ind = 1; if (exist('match', 'var')) for m = 1:length(match) %% match all messages at once s = regexp(obj.events_(ind), match{m}); m_ind = find(~cellfun(@isempty,s)); % m_ind now contains all events, that contain the match for pe = 1:length(m_ind); event_ind = ind(m_ind(pe)); label_timestamp= sscanf(obj.events_{event_ind},'%*s %d %*s'); pos = s{m_ind(pe)} + length(match{m}); obj.labels(l_ind).time = label_timestamp; obj.labels(l_ind).label = strtrim(obj.events_{event_ind}(pos:end)); obj.labels(l_ind).match = match{m}; obj.labels(l_ind).type = 'normal'; obj.labels(l_ind).color = [0.4 0.4 0.4]; l_ind = l_ind + 1; end end end %% hook all matches up to stimuli for t = 1:length(obj.trials) trial = obj.trials(t); %% in case no labels are defined, continue.. if (isempty(obj.labels)) continue; end for l = 1:length(obj.labels) label_timestamps(l) = obj.labels(l).time(1); end % labels are set before or during earlier_labels = find(label_timestamps < trial.trial_end); later_labels = find(label_timestamps > trial.trial_start); % variable is set during trial: common = intersect(earlier_labels, later_labels); if isempty(params.ForcePrecursorLabels) params.ForcePrecursorLabels{2} = 0; end if (~params.ForcePrecursorLabels{2} && ~isempty(common)) trial.labels = obj.labels(common); else % no variables set during, perhaps a precursor variable? if ~isempty(earlier_labels) if t > 1 %% check later than previous trials previous_trial = obj.trials(t-1); later_than_previous = find(label_timestamps >= previous_trial.trial_end); precursors = intersect(earlier_labels, later_than_previous); trial.labels = obj.labels(precursors); else trial.labels = obj.labels(earlier_labels); end end end %% assign variables to trial in field 'type' for l = 1:length(trial.labels) varname = regexprep(trial.labels(l).match,'\s' ,'_'); trial.type.(varname) = trial.labels(l).label; end obj.trials(t) = trial; end