使用数组而不是范围的多项式“LinEst”VBA调用

时间:2014-11-23 23:23:45

标签: excel vba regression interpolation

我无法检索二阶linest函数的系数,并且MsgBox返回错误:“Type mismatch”。

我希望linest函数给出{0,0,1},因为我在本例中使用了平方函数f:x->x²。

Sub RunLinestOld()
Dim vectorX() As Double
Dim vectorY() As Double
Dim theLeastSquareCoef


'redimensionne les vecteurs
ReDim vectorX(1 To 4)
ReDim vectorY(1 To 4)

vectorX(1) = 1
vectorX(2) = 2
vectorX(3) = 3
vectorX(4) = 4

vectorY(1) = 1
vectorY(2) = 4
vectorY(3) = 9
vectorY(4) = 16


'theLeastSquareCoef = Application.LinEst(vectorY, vectorX)
theLeastSquareCoef = Application.LinEst(vectorY, Application.Power(vectorX, Array(1, 2)))

**MsgBox "K is " & Application.Index(theLeastSquareCoef, 1, 2)**

End Sub

2 个答案:

答案 0 :(得分:1)

我用下面的代码实现了这一点。您需要将维度Nx1的矩阵传递给LinEst函数,而不是向量。

Sub RunLinEst()
    Dim vectorX() As Double
    Dim vectorY() As Double
    Dim theLeastSquareCoef


    'you need to define matrix otherwise it doesn't work
    ReDim vectorX(0 To 4, 0 To 0)
    ReDim vectorY(0 To 4, 0 To 0)

    vectorX(0, 0) = 0
    vectorX(1, 0) = 1
    vectorX(2, 0) = 2
    vectorX(3, 0) = 3
    vectorX(4, 0) = 4

    vectorY(0, 0) = 0
    vectorY(1, 0) = 1
    vectorY(2, 0) = 4
    vectorY(3, 0) = 9
    vectorY(4, 0) = 16


    theLeastSquareCoef = Application.LinEst(vectorY, Application.Power(vectorX, Array(1, 2))) 

    Range("F4").Value = Application.Index(theLeastSquareCoef, 1)
    Range("F5").Value = Application.Index(theLeastSquareCoef, 2)
    Range("F6").Value = Application.Index(theLeastSquareCoef, 3)


End Sub

答案 1 :(得分:0)

您需要将linest的结果转换为字符串

 MsgBox("K is " & CStr(Application.Index(theLeastSquareCoef, 1, 2)))