Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sliding window function in julia

Tags:

julia

I am looking to take a collection and slide a window of length 'w' and step size 's' over it to get many sub collections.

I have seen Base.Iterators.partition but that does not allow sliding by less than the window (or partition) length.

I have written something myself that works but I expect there is already a function that does this and I just haven't found it yet.

like image 775
dantheman Avatar asked Mar 27 '20 13:03

dantheman


2 Answers

Assuming z is your Vector and s is your step size and w is window size simply do:

((@view z[i:i+w-1]) for i in 1:s:length(z)-w+1)

Example:

z = collect(1:10)
for e in ((@view z[i:i+4]) for i in 1:2:length(z)-4)
    #do something, try display(e)
end
like image 182
Przemyslaw Szufel Avatar answered Oct 03 '22 17:10

Przemyslaw Szufel


I just found IterTools.jl, it has a partition with custom step size.

julia> for i in partition(1:9, 3, 2)
           @show i
       end
i = (1, 2, 3)
i = (3, 4, 5)
i = (5, 6, 7)
i = (7, 8, 9)
like image 39
Matthijs Cox Avatar answered Oct 03 '22 17:10

Matthijs Cox