Extracting last (non NaN) 200 columns from matrix with varying number of NaNs ending the rows
2 views (last 30 days)
Show older comments
Amy Maddock
on 13 Jul 2017
Commented: Amy Maddock
on 13 Jul 2017
I have pupil size data from an eye tracking experiment. In the experiment, to start each trial the participant looks in the centre of the screen for 1000 ms (prefixation period), then the trial begins. If they look away or blink, the 1000 ms period restarts. So, each trial has a different length prefixation period. When I create a matrix (with each row being a different trial, and each column being a pupil size sample over time) it creates the matrix with the number of columns based on the trial with the longest prefixation period, and then adds varying numbers of NaNs to the end of each other row. I need to extract the last 200 samples (columns) of each trial, but these are not the last 200 columns of the matrix because of the additional NaNs that are added.
At the moment I have this:
Row1 = PreFixBase(1,:); % extract the first row
Row1(isnan(Row1)) = []; %get rid of the NaNs
Row1Base = Row1(end-200+1:end); %extract the last 200 samples / columns
which I do for each row separately and then paste them back together. It works, but is really inefficient (I have 324 rows / trials) and I'm sure there must be a more concise way of doing this, but haven't been able to find the answer.
Any help appreciated.
0 Comments
Accepted Answer
Walter Roberson
on 13 Jul 2017
%first trick: compute row lengths by cumsum of logical tests
temp = cumsum(~isnan(PreFixBase), 2);
used_length = temp(:,end);
%second trick: use code equivalent to sub2ind() to compute starts of rows
nrow = size(PrefixBase, 1);
row_starts = nrow * (used_length - 199) + (1:nrow).';
%third trick: row entries are "nrow" apart in linear memory. Build a
%complete table of linear indices corresponding to the desired entries
linear_indices = bsxfun(@plus, row_starts, nrow * (0:199));
%fourth trick: a 2D array of linear indices gives a 2D array of output
RowBases = PreFixBase(linear_indices);
3 Comments
Walter Roberson
on 13 Jul 2017
I should have said
row_starts = nrow * (used_length - 200) + (1:nrow).';
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!