bigjoepops 2 Report post Posted July 1, 2014 I am trying to create a code section that will take a 1D array and create a moving average array. Sorry if this is a bad description. I want to take x elements of the input array, average them, and put that average in the first element of a new array. Then take the next x elements, average them, and put them as the second element of the new array. I want this done until the array is empty. I have two possible ways to do it, but neither are running as fast as I wanted them to. I want to see if anyone knows of a faster way to conduct this averaging. Thanks Joe Quote Share this post Link to post Share on other sites
GregSands 77 Report post Posted July 1, 2014 (edited) That's not quite a moving average, rather a down-sampling - i.e. Filtered Array is shorter than Input Data. Your first solution is pretty good - just speed it up with a Parallel For Loop. An alternative is to reshape into a 2D array. Both these come out roughly the same speed, about 5x faster on my machine than your solutions above. If you want a true Moving Average (where the result is the same length as the original) I think this suggestion from the NI forums using an FIR filter is nice and simple, although you might look carefully at the first Num values if that's important. Edited July 1, 2014 by GregSands 1 Quote Share this post Link to post Share on other sites
ThomasGutzler 55 Report post Posted July 2, 2014 You have to be careful with the FIR filter the way you're using it because it applies a shift to your data by the amount of "Num of Averages". To fix that, you have to do some padding at both ends of your input data. In this example I just repeat the first and last value: If you run it through a graph it becomes obvious: 2 Quote Share this post Link to post Share on other sites
Tim_S 66 Report post Posted July 2, 2014 Hadn't thought of using a FIR filter. I bench marked a mean method and your FIR method. The FIR method was ~8-9x faster on my system than the mean with standard for loop, and the FIR was ~2-3x faster with the mean method for loop set for parallelism. Quote Share this post Link to post Share on other sites
Gary Rubin 32 Report post Posted July 2, 2014 I don't have LabVIEW installed on this machine and I may be confusing LabVIEW and MATLAB primatives, but I've seen a pretty fast approach that relies on a cumulative summation. Textually, the algorithm is: B=CumulativeSum(A) SlidingAverage(i)=(B(i+windowsize)-B(i))/windowsize Adjust indices as necessary to center your window in the right place and be careful with the edge conditions. Quote Share this post Link to post Share on other sites
bigjoepops 2 Report post Posted July 16, 2014 Thanks for your help. I was able to parallelize the for loop with the mean in it and it helped speed it up. I didn't try the FIR approach. I'm still waiting on verification that the averaging will work for the customer. Quote Share this post Link to post Share on other sites