通过Excel VBA创建关联矩阵的最佳方法是什么?我的数据有45列(可能最终会改变)和12000行(也可能会改变)。我只是在工作表上使用correl
函数,但就像我说的,我的列和行可能会随着时间的推移而改变。
任何帮助将不胜感激!
答案 0 :(得分:4)
我在网上搜索了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
答案 1 :(得分:3)
Application.Run "ATPVBAEN.XLAM!Mcorrel", ActiveSheet.Range("$C$3:$F$6"), _
ActiveSheet.Range("$C$10"), "K", False //"K" might be "C"=column
要运行它,您必须首先启用Data Analysis Toolpak(包)。 您可以通过UI,选项卡数据分析 - >相关矩阵
来使用它这里:
"$C$3:$F$6" - input (square matrix)
$C$10 - output cell
"K" (or "C") - group by columns
false - labels=no
答案 2 :(得分: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
答案 3 :(得分: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