Correlation of two arrays in C#

前端 未结 6 970
挽巷
挽巷 2020-11-29 05:09

Having two arrays of double values, I want to compute correlation coefficient (single double value, just like the CORREL function in MS Excel). Is there some simple one-line

6条回答
  •  抹茶落季
    2020-11-29 05:59

    Public Function Correlation(ByRef array1() As Double, ByRef array2() As Double) As Double
        'siehe https://stackoverflow.com/questions/17447817/correlation-of-two-arrays-in-c-sharp
    
        'der hier errechnete "Pearson correlation coefficient" muss noch quadriert werden, um R-Squared zu erhalten, siehe
        'https://en.wikipedia.org/wiki/Coefficient_of_determination
    
    
        Dim array_xy(array1.Length - 1) As Double
        Dim array_xp2(array1.Length - 1) As Double
        Dim array_yp2(array1.Length - 1) As Double
    
        Dim i As Integer
        For i = 0 To array1.Length - 1
            array_xy(i) = array1(i) * array2(i)
        Next i
        For i = 0 To array1.Length - 1
            array_xp2(i) = Math.Pow(array1(i), 2.0)
        Next i
        For i = 0 To array1.Length - 1
            array_yp2(i) = Math.Pow(array2(i), 2.0)
        Next i
    
    
        Dim sum_x As Double = 0
        Dim sum_y As Double = 0
        Dim EinDouble As Double
    
        For Each EinDouble In array1
            sum_x += EinDouble
        Next
        For Each EinDouble In array2
            sum_y += EinDouble
        Next
    
        Dim sum_xy As Double = 0
        For Each EinDouble In array_xy
            sum_xy += EinDouble
        Next
    
        Dim sum_xpow2 As Double = 0
        For Each EinDouble In array_xp2
            sum_xpow2 += EinDouble
        Next
    
        Dim sum_ypow2 As Double = 0
        For Each EinDouble In array_yp2
            sum_ypow2 += EinDouble
        Next
    
        Dim Ex2 As Double = Math.Pow(sum_x, 2.0)
        Dim Ey2 As Double = Math.Pow(sum_y, 2.0)
    
        Dim ReturnWert As Double
        ReturnWert = (array1.Length * sum_xy - sum_x * sum_y) / Math.Sqrt((array1.Length * sum_xpow2 - Ex2) * (array1.Length * sum_ypow2 - Ey2))
        Correlation = ReturnWert
    End Function
    

提交回复
热议问题