# Array averaging

## Recommended Posts

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

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 by GregSands
• 1

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

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.

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.

• 2 weeks later...

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.

• ### Similar Content

• #### DevOps Engineer -- for audio test & measurement in Boston (LISTEN)

By J D,

• 0 replies
• 2,012 views
• #### MoveBlock duration

By bna08,

• 5 replies
• 1,286 views
• #### Hooovahh Array VIMs

By hooovahh,

• 6,674 views
• #### [CR] Hooovahh Array VIMs

By hooovahh,

• 24 replies
• 8,511 views
• #### populate ring array with data, serial communication

By WILSTi,

• 0 replies
• 5,593 views
×