dantheman
dantheman

Reputation: 131

sliding window function in 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.

Upvotes: 5

Views: 2588

Answers (3)

Matthijs Cox
Matthijs Cox

Reputation: 121

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)

Upvotes: 3

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42194

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

Upvotes: 7

Nils Gudat
Nils Gudat

Reputation: 13800

Have you looked at RollingFunctions? It seems to me that it does what you're looking for, it has rolling and running functions which take a function, a vector, and a windows size as input and return the result of applying the function over successive windows.

Upvotes: 1

Related Questions