MATLAB: Extract numbers from lines in a txt file. Onset times from experimental data.

behavioralextractfmriget linetxt

Hi,
This problem should be familiar to people working with behavioral data, but I was unable to find a previous answer that would work for me.
I am trying to extract the onset times of certain conditions during an experiment.
The data is organised as in the enclosed file. I want to extract the lines starting with:
'WaitForScanner.OnsetTime'
'Tune.OnsetTime'
and
'ImagineMelody.OnsetTime'
and then extract the numbers at the end of these lines (5-digit onset times in ms) as variables,
work with them a bit in matlab: subtract scanneronset from tuneonset and imagineonset, and convert them to seconds,
and output them in two separate txt files (tuneonset.txt and imagine.txt).
When that works for one subject, I plan to loop over many subjects and also different sessions per subject (different txt file, same principle).
Best,
Andreas

Best Answer

Carrying on from the above that just diddled with the file format to be able to get the data; the following seems to work:
filename = 'Imagine_simple-1-1.txt';
onsets={'Tune.OnsetTime';'ImagineMelody.OnsetTime';'WaitForScanner.OnsetTime'};
imaginefile = 'ImagineMelody.OnsetTime.txt';
tunefile = 'Tune.OnsetTime.txt';
txt=importdata(filename); % read data file to cellstr array
txt=strrep(txt,char(0),''); % and convert to char() from 2-byte encoding
txt=strrep(txt,char(255:-1:254),''); % finally, clean up BOM mess...
fnGrabNum=@(t) (str2double(extractAfter(txt(contains(txt,t)),':'))/1000); % return numeric data
times=cellfun(fnGrabNum,onsets,'UniformOutput',0); % get the wanted sections
elapsedtimes=seconds(cell2mat(cellfun(@(t) t-times{3},times(1:2),'UniformOutput',0).')); % times from reference time
Results in:
>> elapsedtimes
elapsedtimes =
20×2 duration array
3.233 sec 16.232 sec
55.402 sec 42.23 sec
81.644 sec 94.642 sec
133.88 sec 120.64 sec
160.07 sec 173.07 sec
212.27 sec 199.07 sec
238.45 sec 251.46 sec
290.68 sec 277.46 sec
316.91 sec 329.91 sec
369.07 sec 355.9 sec
395.25 sec 408.25 sec
447.46 sec 434.25 sec
473.69 sec 486.69 sec
525.86 sec 512.69 sec
552.03 sec 565.04 sec
604.22 sec 591.03 sec
630.4 sec 643.41 sec
682.6 sec 669.41 sec
708.79 sec 721.79 sec
761.16 sec 747.79 sec
>>