Consulting

Results 1 to 6 of 6

Thread: Average of n elements in an array

  1. #1
    VBAX Regular
    Joined
    Jul 2010
    Posts
    26
    Location

    Average of n elements in an array

    Hi Everybody,

    I am having a problem averaging certain sections of an array in VBA. What I have is an array of around 50,000 numerical entries. I need to take the average of the first ten, second ten, third ten... etc. and store this number in a new array. I would prefer to do this without using too many nested loops however I won't disregard this option. Any thoughts on how to approach this?

    Thanks a lot, I appreciate any and all help!

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    [vba]

    StartPos = 11
    NumValues = 10

    ReDim aryResults(1 To NumValues)
    For i = StartPos To StartPos + NumValues - 1

    aryResults(i - StartPos + 1) = aryNumbers(i)
    Next i
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    [VBA]Sub foo()
    Dim currentIndex as Long
    ' get someArray
    currentIndex = 1

    Do Until currentIndex + 10 > UBound(someArray)
    MsgBox AverageOfSubArray(someArray, currentIndex, 10)
    currentIndex = currentIndex + 10
    Loop

    End Sub

    Function AverageOfSubArray(myArray as Variant, startIndex as Long, elementCount as Long) as Double
    Dim runningTotal as Double
    Dim i as Long

    For i = startIndex to (startIndex + elementCount -1)
    runningTotal = runningTotal + Val(myArray(i))
    Next i
    AverageOfSubArray = runningTotal / elementCount
    End Function[/VBA]

  4. #4
    VBAX Regular
    Joined
    Jul 2010
    Posts
    26
    Location
    Thanks!

  5. #5
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    I forgot one line in my code, namely how to get the average

    [vba]

    MsgBox Application.Average(aryResults)
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  6. #6
    VBAX Regular
    Joined
    Jul 2010
    Posts
    26
    Location
    Haha I figured that something was missing but it works great now. Thanks again guys!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •