3

通过 Excel VBA 创建相关矩阵的最佳方法是什么?我的数据有 45 列(最终可能会改变)和 12000 行(也可以改变)。我打算只使用correl工作表上的函数,但就像我说的,我的列和行可能会随着时间而改变。

任何帮助将不胜感激!

4

4 回答 4

4
 Application.Run "ATPVBAEN.XLAM!Mcorrel", ActiveSheet.Range("$C$3:$F$6"), _
    ActiveSheet.Range("$C$10"), "K", False //"K" might be "C"=column

要运行它,您必须首先启用数据分析工具包(包)。您可以通过 UI、选项卡 Data Analysis->correlation matrix 使用它

这里:

"$C$3:$F$6" - input (square matrix)
$C$10 - output cell
"K" (or "C") - group by columns
false - labels=no
于 2013-04-16T20:27:15.840 回答
3

我在网上搜索了 VBA 相关矩阵代码,但没有找到任何实质内容。自己做了一些编码,它并不漂亮,但它确实完成了工作。此代码将在最后一个数据系列的右侧创建一个矩阵。

Sub CorrelationMatrix()

Dim y As Range
Dim z As Range

funds = Application.Workbooks("VBAcorrelation").Worksheets("Sheet1").Cells(1,       Columns.Count).End(xlToLeft).Column
rader = 0
For x = 1 To funds
        nyrad = Cells(Rows.Count, x).End(xlUp).Row
        If nyrad > rader Then
        rader = Cells(Rows.Count, x).End(xlUp).Row
    End If
Next x



p = 1
u = 2

For h = 1 To funds
For u = 1 To funds

        Set y = ActiveSheet.Range(Cells(2, h), Cells(rader, h))
        Set z = ActiveSheet.Range(Cells(2, u), Cells(rader, u))

  Correl = WorksheetFunction.Correl(y, z)

 Worksheets("Sheet1").Cells(h + 1, funds + u + 3).Select
 ActiveCell = Correl

 Next u
 Next h

MsgBox "Done with Matrix"
End Sub
于 2013-07-11T13:42:36.333 回答
1

这对函数以矩阵形式为您提供结果(选择它应该出现的范围,引入公式,然后按 F2,然后按 Ctrl+shift+enter 以查看值)。复制两者并粘贴到 VBA 编辑器上。

'function to create a correlation matrix given the data
Function CorrMatriz(Mat_data As Variant)
Dim i As Integer, j As Integer, corr As Variant, M1 As Variant, M2 As Variant
ReDim corr(1 To Mat_data.Columns.Count, 1 To Mat_data.Columns.Count)

ReDim M1(1 To Mat_data.Rows.Count, 1 To 1)
ReDim M2(1 To Mat_data.Rows.Count, 1 To 1)

For i = 1 To Mat_data.Columns.Count
    M1 = ExtraeMatriz(Mat_data, i)
    For j = 1 To Mat_data.Columns.Count
        M2 = ExtraeMatriz(Mat_data, j)
        corr(i, j) = Application.Correl(M1, M2)
    Next j
Next i
CorrMatriz = corr
End Function`

' function to extract one column
enter code here
Function ExtraeMatriz(Matriz As Variant, columna As Integer)
Dim i As Integer, data_final As Variant
ReDim data_final(1 To Matriz.Rows.Count, 1)
For i = 1 To Matriz.Rows.Count
    data_final(i, 1) = Matriz(i, columna)
Next i
ExtraeMatriz = data_final
End Function
于 2019-10-02T09:00:55.227 回答
0

它工作正常:

Option base 1  
      Function MCorrelation(rango As Range) As Variant
        Dim x As Variant, y As Variant, s As Integer, t As Integer, c() As Variant
        ReDim c(rango.Columns.Count, rango.Columns.Count)
        For i = 1 To rango.Columns.Count Step 1
         For j = 1 To i Step 1
        c(i, j) = Application.Correl(Application.Index(rango, , i), Application.Index(rango, , j))
         Next j
        Next i
         MCorrelation = c
        End Function
于 2017-01-07T17:29:39.240 回答