Create overlapping and non-overlapping sliding windows in MATLAB

北城以北 提交于 2019-12-02 05:49:52

To extract out overlapping blocks, I recommend using bsxfun to create the indices and subset the matrix whereas non-overlapping blocks you can simply use reshape.

Overlapping

ind = bsxfun(@plus, (1 : blksze), (0 : numel(Data) - blksze).');

The advantage of this method is that it uses broadcasting to generate the right indices per block. This would thus be a 2D matrix where each row are the indices required to grab the data for the right block and the number of columns is dictated by the block size.

Non-overlapping

ind = reshape(1 : numel(Data), [], numel(Data) / blksze).';

This simply reshapes the vector so that each row would be a unique set of indices that increases by 1 and the number of columns is dictated by the block size.


Finally, just index into Data to get what you need:

blocks = Data(ind);

Here's a running example using 6 elements:

>> rng(123); Data = rand(1, 6)

Data =

    0.6965    0.2861    0.2269    0.5513    0.7195    0.4231

With a block size of 2, or blksze = 2, here's what we get for both overlapping and non-overlapping:

>> blksze = 2;
>> indno = reshape(1 : numel(Data), [], numel(Data) / blksze).';
>> indo = bsxfun(@plus, (1 : blksze), (0 : numel(Data) - blksze).');
>> blockno = Data(indno)

blockno =

    0.6965    0.2861
    0.2269    0.5513
    0.7195    0.4231

>> blocko = Data(indo)

blocko =

    0.6965    0.2861
    0.2861    0.2269
    0.2269    0.5513
    0.5513    0.7195
    0.7195    0.4231

Caveat

This code does no error checking in that we assume that there are enough blocks to capture all of your data. If you have the number of elements in Data to be incompatible with the block size to capture all of the data in blocks of all the same size, an error will occur upon indexing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!