Quick MATLAB question. What would be the best/most efficient way to select a certain number of elements, 'n' in windows of 'm'. In other words, I want to select the first 50 elements of a sequence, then elements 10-60, then elements 20-70 ect. Right now, my sequence is in vector format(but this can easily be changed).
EDIT: The sequences that I am dealing with are too long to be stored in my RAM. I need to be able to create the windows, and then call upon the window that I want to analyze/preform another command on.
Do you have enough RAM to store a 50-by-nWindow array in memory? In that case, you can generate your windows in one go, and then apply your processing on each column
To complement Kerrek's answer: if you want to do it in a loop, you can use something like
There's a slight issue with the description of your problem. You say that you want "to select the first 50 elements of a sequence, then elements 10-60..."; however, this would translate to selecting elements:
That first sequence should be 0-10 to fit the pattern which of course in MATLAB would not make sense since arrays use one-indexing. To address this, the algorithm below uses a variable called startIndex to indicate which element to start the sequence sampling from.
You could accomplish this in a vectorized way by constructing an index array. Create a vector consisting of the starting indices of each sequence. For reuse sake, I put the length of the sequence, the step size between sequence starts, and the start of the last sequence as variables. In the example you describe, the length of the sequence should be 50, the step size should be 10 and the start of the last sequence depends on the size of the input data and your needs.
Create some sample data:
Create a vector of the start indices of the sequences:
Create an array of indices to index into the data array:
Finally, use this index array to reference the data array:
Use
(start : step : end)
indexing:v(1:1:50)
,v(10:1:60)
, etc. If thestep
is1
, you can omit it:v(1:50)
.Consider the following vectorized code:
The result (truncated for brevity):
In fact, the code was adapted from the now deprecated SPECGRAM function from the Signal Processing Toolbox (just do
edit specgram.m
to see the code).I omitted parts that zero-pad the sequence in case the sliding windows do not evenly divide the entire sequence (for example
x=1:105
), but you can easily add them again if you need that functionality...