Message Boards Message Boards

How to generalize a MovingAverage list replacements

Posted 9 years ago

Hi, I am trying to write a function that will repeat this process an arbitrary amount of times. The process is to take the moving average of a list, and then Riffle back into the original list. Each time given the mean value between consecutive numbers in the list. I'd like to us a function to tell how many times the process should be repeated for any given list. So that for the second call to the function the consecutive elements of the list are again divided in half and then Riffled back into the previous list. This seems like a good job for the Nest or Fold functions. However I haven't had much luck. Any suggestions or alternative methods? Thus far I've tried the code below, which defines a functions to compute the moving average and then Riffles afterward. V1 below. And code the Riffles explicitly in the function. However I fail to properly Nest the function, as it fails after only 1 Nesting call. V2 below.

x = N@Range@10;
s[x_] := MovingAverage[x, 2];
Riffle[#, Nest[s, #, #2]] &[x, 1]

scheduler[{x_, y_}] :=
  Block[{tempSchedule},
   tempSchedule = x;
   tempSchedule = 
    Riffle[tempSchedule, MovingAverage[tempSchedule, y]]
   ];
Nest[scheduler, {x, 2}, 1]
POSTED BY: Pat Mac

Well, I assume that you solved that, but in case someone else is looking for a solution Nest repeatedly applies the function on the result returned `by the previous function call. BUT, you function is expecting a second element in the list for its input is missing. This is why you can operate it only once and not more, since in the second time there is no such element the input for the second time in your case is {numbers returned by the Riffle....} and it should be {{numbers returned by the Riffle...},y} after this correction the actual result that your should be expecting is First[...result of the modified scheduler...]

With a little bit enhancing your code you could also 1. Eliminate use of the Block 2. operating the Nest inside the body of the scheduler 3. Using First[.] function (all in one liner)

yehuda

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract