Reshape vector with a step and window size

2019-06-13 17:18发布

问题:

I have a vector, for example

A = [1 2 3 4 5 6 7 8]

I want to "reshape" it to matrix with windowsize=4 and stepsize=2, such that the resulting matrix is

b = [ 1   3   5;   
      2   4   6;   
      3   5   7;   
      4   6   8 ]

回答1:

You can set up an indexing matrix, then just index into A...

A = [1 2 3 4 5 6 7 8];

windowsize = 4;
stepsize = 2;

% Implicit expansion to create a matrix of indices
idx = bsxfun( @plus, (1:windowsize).',  0:stepsize:(numel(A)-windowsize) );

b = A(idx);

Note; in this case idx and b are the same, but you need the final indexing step assuming A isn't just consecutive integers in your real example.