programming - How to find first list element that differs from average of N previous elements by more than a given amount?
Given a list of real numbers, I need to write a function that returns the value of the first element in the list that differs from the mean of the previous $N$ elements by greater than $P$ standard deviations of those same elements. (I use mean and standard deviation as sample functions, I may decide to use something else.)
Clearly, I can write a loop to do this, but I'd like to use functional programming techniques to do this, and continue to learn better Mathematica programming style. Select[ ]
looked promising, but I see no way to involve the previous list elements in the selection criterion.
Thanks in advance for your help! Tom
Answer
Here's an attempt (without select)
lst = {1, 2, 2, 1, 2, 5, 2, 4};
n = 4;
p = 1;
Flatten[If[Abs[Take[#, -1] - Mean[Drop[#, -1]]][[1]] > p *StandardDeviation[Drop[#, -1]],
Take[#, -1], {}] & /@ Partition[lst, n + 1, 1, 1]] // First
Alternatively with Select.
Select[Partition[lst, n + 1, 1, 1],
Abs[Take[#, -1] - Mean[Drop[#, -1]]][[1]] > p*StandardDeviation[Drop[#, -1]] &]
// First // Last
For a more efficient implementation - see Mr Wizard's answer
Comments
Post a Comment