Quadratic Polynomial fit with LINEST()
Hi. This is slightly better...
Sub Example()
Dim Ans
Ans = LinReg2([A1:A10], [B1:B10])
End Sub
Function LinReg2(Ys, Xs)
Dim J As Long
Dim Yy, Xx
Dim Y, X
Dim v 'Solution Vector
Dim d
Set d = CreateObject("Scripting.Dictionary")
' Load data...
With WorksheetFunction
Yy = .Transpose(Ys.Value)
Xx = .Transpose(Xs.Value)
' Save only valid numeric pairs
For J = LBound(Yy) To UBound(Yy)
If (IsNumeric(Yy(J)) And IsNumeric(Xx(J))) Then
d.Add d.Count + 1, Array(Yy(J), Xx(J))
End If
Next J
Y = .Index(d.items, 0, 1)
X = .Index(d.items, 0, 2)
End With
With ActiveWorkbook
.Names.Add "Y", Y
.Names.Add "X", X
v = [LINEST(Y,X^{1,2},TRUE,FALSE)]
.Names("Y").Delete
.Names("X").Delete
End With
' Three Coefficients: a*x^2+b*x+c
Debug.Print v(1) 'a
Debug.Print v(2) 'b
Debug.Print v(3) 'c
LinReg2 = v
End Function
--
HTH :)
Dana DeLouis
Windows XP & Office 2007
<snip
"SamCar" wrote in message
...
I have the following in a spreadsheet for example:
120.82 165.97 27546.65
NA NA NA
99.61 157.86 24920.88
216.03 137.9 19015.91
NA NA NA
NA NA NA
NA NA NA
NA NA NA
NA NA NA
99.61 161.05 25937.26
124.51 193.57 37468.83
99.61 167.15 27938.5
NA NA NA
NA NA NA
These columns are Y, X and X^2 respectively. I ultimately want to use
LINEST() for a quadratic polynomial fit on the rows not displaying NA
(the
rows not displaying NA satisfy a previous condition elsewhere on the
spreadsheet). The number of rows with NA will be variable with each
different
application of the function. I have written a crude function in VBA using
help from this website and elsewhere, and some basic matlab programming
knowledge, for a straight line fit (i.e. just on Y, X):
<snip
However I can't do the same for the quadratic fit [in Excel,
=LINEST(Y,X^{1,2},True,False)] because VBA doesn't allow the abbreviation
X^{1,2}. How can I change my program to prepare Y and X(as an n by 2
matrix
with X in the first column and X^2 in the second) removing the 'NA's as
before? Or alternatively, preparing the three columns as arrays and then
joining the X and X^2 columns before applying the function? I'm very new
to
VBA so I'm not very good at array manipulation.
Many thanks,
Sam
|