arrays - Create overlapping and non-overlapping sliding windows in MATLAB -


i trying create overlapping , non-overlapping blocks of data array data containingn elements. how can correctly form sub-arrays of data n , blksze? following code non-overlapping blocks throws error because of number of elements exceed when creating sub-blocks. example, let data = [1,2,3,4,5,6],

  • for overlapping case should : block size blksze = 2, block1 = [1,2], block2 = [2,3], block3 = [3,4], block4 = [4,5], block5 = [5,6]

  • for non-overlapping : block size blksze = 2, block1 = [1,2], block2 = [3,4], block3 = [5,6]

code snippet

n= 100; n = 4; data = randi([1 n],1,n); blksze = 10; nblocks = n / blksze; counter = 1; = 1 : nblocks     block{i} = data(counter : counter + blksze - 1);     counter = blksze + 1; end 

to extract out overlapping blocks, recommend using bsxfun create indices , subset matrix whereas non-overlapping blocks can use reshape.

overlapping

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

the advantage of method uses broadcasting generate right indices per block. 2d matrix each row indices required grab data right block , number of columns dictated block size.

non-overlapping

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

this reshapes vector each row unique set of indices increases 1 , number of columns dictated block size.


finally, index data need:

blocks = data(ind); 

here's 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 block size of 2, or blksze = 2, here's both overlapping , 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 no error checking in assume there enough blocks capture of data. if have number of elements in data incompatible block size capture of data in blocks of same size, error occur upon indexing.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -