1

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 ]
Wolfie
  • 27,562
  • 7
  • 28
  • 55
Sangeetha R
  • 139
  • 7
  • Can you please further elaborate, what do you mean with "windowsize" and "stepsize"? Also, this is no reshaping, since matrix values seem to be present multiple times in the result `b`!? – HansHirse Feb 27 '19 at 09:30
  • 'window size' represent the number of elements in a column in output matrix 'b'. Here first 4 elements fill the first column in 'b', after the step size interval(here 2) next 4 elements from A fill second column in 'b', again after step size interval next 4 elements from A fill third column in 'b' and so on – Sangeetha R Feb 27 '19 at 09:45

1 Answers1

4

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.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • Using the same approach, but using "implicit expansion" instead of `bsxfun` you could use this code: `idx = (1:s:(numel(A)-s))+(0:w-1).'`. – obchardon Feb 27 '19 at 11:30
  • 1
    @obchardon Yes, after MATLAB R2016b these are equivalent... and of course you've made that look a lot more compact than using `bsxfun` primarily because you shortened the variable names ;) – Wolfie Feb 27 '19 at 11:34
  • 1
    I got another solution for this problem by using buffer function: idx = buffer(1:8,windowsize,stepsize,'nodelay'); – Sangeetha R Feb 28 '19 at 10:22