I'm having great difficulty coding the following in MATLAB: Suppose you have the following vector:
a
b
c
d
e
f
g
h
...
Specifying an (even) window size, create the following matrix of dimensions L
rows by n
columns (example, L = 4
):
a c e ...
b d f ...
c e g ...
d f h ...
Even more difficult is taking a vector of arbitrary length, specifying the number of windows, and optimizing (maximizing) the window size so less values at the end of the vector are dumped.
Short answer
bsxfun
is your friend in this case. The following one-liner (assuming you knowL
andv
is your vector) does what you wantExplanation
To try it out and understand it, lets have a further look. The idea is to first create a vector that determines, where the windows start in the
v
vector. Windows start everyL/2
entries (L
is even, so we can divide). But how many windows fit? We can rely on MATLAB to figure this out by saying:Here we just only need to specify that
L/2
entriesNow, the rest of the example:
There are many ways to do this in MATLAB by manipulating indices, procedural approaches, vectorized solutions, etc. Yet, I can't help but think of how simple some tasks might be, if MATLAB had a wee bit of support for functional style of programming. In that spirit, I present the following solution. Ensure that you don't already have any values in those variables at definition time.
Now try it with a test vector:
The above solution discards the final values at the end of the vector that don't fit a length
L
after partition. You can now build up on this to handle other arrangements and figure out optimal window lengths for minimal end wastage, etc.Create the matrix of indices into your vector. For L=4 (I assume you are overlapping by L/2), the indices are [1,2,3,4;3,4,5,6;5,6,7,8] etc. Let x = 1:L, y = L/2, the vector of indices is x+0y,x+1y,x+2y, and so on.
Here's a general way to do what you want:
1) Calculate the appropriate window width (and corresponding shift)
2) Determine the start indices of each column by iterating from 1 by the amount you want to shift the window each column, up to the final value. Make this a row vector.
3) Use
bsxfun
to expand this to a matrix of indices.4) Use the indices to get the values from the original vector.