Weighted Average PowerShell Function


Recently I found myself in a need to calculate a ton of weighted averages. I thought that the Internet will be full of little PowerShell functions for that, but I couldn’t find a single one, so here’s the one I wrote in a hurry.


function weightedAverageArray([int[]]$averageArray, [int[]]$weightArray){

    ####Check if the Values count and the Weights count is the same
    if($averageArray.count -eq $weightArray.count){

        ####Check if Values count is not 1
        if($averageArray.count -ne 1){

            ####Sum up all the Weights
            $weightSum = ($weightArray | Measure-Object -Sum).Sum

            ####Index In Variable
            $indexIn = 0

            ####Container Array
            $averageNodes = @()

            ####Iterate through Values
            foreach($average in $averageArray){

                ####Calculate Weighted Average
                $averageNode = ([math]::round($average))*(($weightArray[$indexIn])/$weightSum)

                ####Add to Container Array
                $averageNodes+=$averageNode

                ####Advance Counter
                $indexIn++
            }

            ####Sum up the results
            $averageNodesSum = ($averageNodes| Measure-Object -Sum).sum

            ####Return Result
            return $averageNodesSum
        } else {
            ####If Values count is 1, return the Value
            return $averageArray
        }
    } else {
        ####If Values and Weights are not the same count
        write-host "Values and Weights are not the same count: Values:"$averageArray.count"Weights:"$weightArray.count -ForegroundColor Red
    }
}


The parameters passed to the Function can be formatted in a couple of ways.
Pass directly
Just pass the Values and their corresponding weights when you are calling. The following calculates 0/32 and 100/32. It returns 50.
weightedAverageArray -averageArray ("0","100") -weightArray ("32","32")

Pass Array
For this one we have an array that contains Value and Weight Members. 
Value
Weight
130
258
295
125
165
176
297
269
198
138
251
276
264
182
174
218
71
89
228
59

We want to get the weighted average for the first 5 pairs.
weightedAverageArray -averageArray ($testArray.Value[1..5]) -weightArray ($testArray.Weight[1..5])


Comments