Correlation Coefficient routine in Visual Basic

(c) 2013 by Barton Paul Levenson


Language:
Basic

Dialect:
Microsoft Visual Basic Express 2010

Discussion:
This routine finds the Pearson Product-Moment Correlation Coefficient between two data series. You pass it two arrays of double-precision numbers, presumably of equal size, and the array size.


    ' Correl finds the correlation between two series of numbers.
    Function Correl(ByVal X() As Double, ByVal Y() As Double, _
    ByVal Num As Integer) As Double
        Dim muX As Double, muY As Double
        Dim Sxx As Double, Sxy As Double, Syy As Double
        Dim sumX As Double, sumY As Double
        Dim sumX2 As Double, sumXY As Double, sumY2 As Double

        sumX = 0
        sumY = 0
        sumX2 = 0
        sumY2 = 0
        sumXY = 0

        For L As Integer = 1 To Num
            sumX += X(L)
            sumY += Y(L)
            sumX2 += X(L) * X(L)
            sumY2 += Y(L) * Y(L)
            sumXY += X(L) * Y(L)
        Next L

        muX = sumX / Num
        muY = sumY / Num
        Sxx = sumX2 - Num * muX * muX
        Syy = sumY2 - Num * muY * muY
        Sxy = sumXY - Num * muX * muY

        Return Sxy / Sqrt(Sxx * Syy)
    End Function ' Correl


Page created:06/29/2013
Last modified:  06/29/2013
Author:BPL