Suppose I have a long data vector y, as well as some indexes. I want to extract a short fragment or window around each index.
For example, suppose I want to build a matrix containing 64 samples before and 64 samples after each value that is less than three. This is trivial to do for the loop:
WIN_SIZE = 64;
% Sample data with padding
data = [nan(WIN_SIZE,1); randn(1e6,1); nan(WIN_SIZE,1)];
% Sample events, could be anything
index = find(data < 3);
snippets = nan(length(index), 2*WIN_SIZE + 1);
for ii=1:length(index)
snippets(ii,:) = data((index(ii)-WIN_SIZE):(index(ii)+WIN_SIZE));
end
However, this is not incredibly fast. Is there a way to vectorize (or otherwise speed up) this operation?
(In case this is not clear, the index can be anything and may not necessarily be a data property, I just wanted something to simply illustrate the idea.)
source
share