我使用此代码从描述销售的从1到12重复的序列生成转移概率矩阵。
如何在Excel中使用公式实现此代码
我没有使用VBA的经验,我在excel中尝试过,但失败了。
x <- e$Range
p <- matrix(nrow = 12, ncol = 12, 0)
for (t in 1:(length(x) - 1)) p[x[t], x[t + 1]] <- p[x[t], x[t + 1]] + 1
for (i in 1:12) p[i, ] <- p[i, ] / sum(p[i, ])
p
这12个值中每个单元格中每个值的转移概率。
提前谢谢你,致以问候
发布于 2019-04-10 15:29:55
假设您的excel工作表中有以下数据,从X
的位置A1
开始:
如果要将两个表放在不同的位置,请使用新位置修改宏中的以下变量:
请注意,矩阵是用0和1填充的,因为您没有将示例数据放在帖子中
下面是一种使用宏实现所需功能的方法:
Sub TransitonProbabilityMatrix()
Dim startRowNumX, startColNumX, startRowNumP, startColNumP, sizeMatrix As Integer
startRowNumX = 1
startColNumX = 1
startRowNumP = 3
startColNumP = 1
sizeMatrix = startColNumX
While (Not IsEmpty(Cells(startRowNumX, sizeMatrix)))
sizeMatrix = sizeMatrix + 1
Wend
sizeMatrix = sizeMatrix - startColNumX
For i = startColNumX + 1 To startColNumX + sizeMatrix - 2
Cells(Cells(startRowNumX, i) + startRowNumP, Cells(startRowNumX, i + 1) + startColNumP) = Cells(Cells(startRowNumX, i) + startRowNumP, Cells(startRowNumX, i + 1) + startColNumP) + 1
Next
For i = startRowNumP + 1 To startRowNumP + sizeMatrix - 1
For j = startColNumP + 1 To startColNumP + sizeMatrix - 1
Cells(i, j) = Cells(i, j) / WorksheetFunction.Sum(ActiveSheet.Range(Cells(i, startColNumP + 1), Cells(i, startColNumP + sizeMatrix)))
Next
Next
End Sub
该Sub首先搜索矩阵的大小,然后应用转换。
https://stackoverflow.com/questions/55614141
复制相似问题