Possible Duplicate:
How to Map a subset of list elements to a function?
I want to evaluate a function using arguments from a sliding window over a list.
As an example, lets use Mean
as the function, window size as 3
, and the list as Range[1, 10]
.
The results I am looking for are:
{ Mean[{1,2,3}], Mean[{2,3,4}], ... Mean[{8,9,10}] }
i.e.
{2, 3, 4, 5, 6, 7, 8, 9}
Is there something in Mathematica
that can do this, or an improvement on the following implementations?
Implementation #1
Slide1[f_, expr_, n_Integer] :=
Module[{myExpr},
myExpr = RotateRight[expr, 1];
Nest[
Delete[#, -1] &,
Map[(
myExpr = RotateLeft[myExpr, 1];
f[myExpr[[1 ;; n]]]
) &, myExpr],
n - 1]
];
In[]:= Slide1[Mean, Range[1, 10], 3]
Out[]:= {2, 3, 4, 5, 6, 7, 8, 9}
Rotating can not be that efficient, can it?
In[]:= AbsoluteTiming[Slide1[Mean, Range[1, 100000], 3]][[1]]
Out[]:= 3.529240
Implementation #2
Slide2[f_, expr_, n_Integer] :=
Module[{result, i},
result = {};
For[i = 1, i <= Length[expr] - n + 1, i++,
AppendTo[result, f[expr[[i ;; i + n - 1]]]];
];
result
]
In[]:= Slide2[Mean, Range[1, 10], 3]
Out[]:= {2, 3, 4, 5, 6, 7, 8, 9}
Please ... For
and AppendTo
In[]:= AbsoluteTiming[Slide2[Mean, Range[1, 100000], 3]][[1]]
Out[]:= 27.811511