Extract windows from signals
1 view (last 30 days)
Show older comments
Hello to all,
i have a large signal and a vector containing moments of time (in the form of index). The vector represents moments in time where I must extract a window from the signal. I can do it with a for loop, but given the size of the signal (36million points), this takes too long. Here is my code
for i = 1:1:length(vector_index)
windows = signal( vector_index(i):vector_index(i) + window_length);
end
I there a more straightforward (and optimal) piece of code which I can insert?
Best regards,
Jean
1 Comment
Jan
on 5 Oct 2011
Currently your code does not calculate anything. A better solution can be found depending on the actual calculations, but without knowing the details, the shown code looks optimal. What is "vector_index"?
Accepted Answer
Sean de Wolski
on 5 Oct 2011
No need for loops:
v = 1:40; %sample vector
wl = 3; %window length
idx = [3 7 21]'; %start indexes
v2 = v(bsxfun(@plus,idx,0:wl-1)) %extracted indexes
And if you risk having an index within wl of the end of the vector, use min to keep them out.
v2 = v(min(bsxfun(@plus,idx,0:wl-1),length(v)))
There will be duplicates at the end - you can do with them what you wish.
2 Comments
Dr. Seis
on 5 Oct 2011
This is a neat trick!
I ran a test using v = 1:1e6, wl = 8000, and then made idx be 9000 random starting points between 1 and 900000.
With Sean de's method, v2 was populated in 1.4 seconds (give or take a few hundredths of a second). By doing it using "for loops" v2 was populated in 1.5 seconds. Not a huge gain, but a neat trick nonetheless!
More Answers (1)
Dr. Seis
on 5 Oct 2011
Are you processing that window of samples inside the loop where you create your "windows" variable. Or are you saving it to do processing elsewhere in your code? If you are using "windows" outside of your for loop, then you should initialize windows before the for loop as:
windows = zeros(length(vector_index),window_length);
Then you would change "windows" inside your for loop to:
windows(i,:) = signal( vector_index(i):vector_index(i) + window_length);
I am not sure if there is a significantly faster way of doing this, how many windows are you extracting from your data and what is the window length?
5 Comments
Dr. Seis
on 5 Oct 2011
Oh, actually the "windows" inside your for loop should be:
windows(i,:) = signal( vector_index(i):vector_index(i) + window_length - 1);
so that there are actually (in your case) exactly 3500 points in your window (otherwise you get 3501).
Does pre-allocating help any?
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!