Greetings,
As previously stated, the simplest way to fill in the missing data points is to apply "Linear Interpolation". Basically this involves calculating the gradient between the two known data values and then using it to calculate the vertical offset from one of the known data points.
e.g. Given two data points
(X1=1, Y1=10)
and
(X4=4, Y4=25)
we can calculate the Y values for the missing X2 and X3 as follows;
<br />
Gradient = (Y2-Y1)/(X2-X1)<br />
Y2 = Y1 + Gradient*(X2-X1)<br />
Y3 = Y1 + Gradient*(X3-X1)<br />
Automatically filling in the gaps in your data array is simply a matter of locating a block of consecutive missing data points in the array and then applying the above formulas to each point in the block.
e.g.
Private Sub ArrayInterpolation(ByRef arr() As Double)
Dim FirstMissingItem As Integer = 0
For Current As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
If arr(Current) = 0.0 Then
If FirstMissingItem = 0 Then
FirstMissingItem = Current
End If
Else
If FirstMissingItem > 0 Then
Dim Gradient As Double = (arr(Current) - arr(FirstMissingItem -1)) _
/(Current - FirstMissingItem + 1)
For MissingItem As Integer = FirstMissingItem To (Current - 1)
arr(MissingItem) = arr(FirstMissingItem - 1) _
+ Gradient * (MissingItem - FirstMissingItem + 1)
Next
End If
FirstMissingItem = 0
End If
Next
End Sub
The outer loop identifies blocks of consecutive missing data items. It sets the
FirstMissingItem
variable to the index of the first missing item encountered; when a second known value is encountered it verifies that the block was preceded by a known data value and then proceeds to the interpolation section. At this point
Current
will hold the index of the first known data item following the block. The gradient is then calculated between the two known data points (
FirstMissingItem-1
and
Current
) and is used by the inner loop to interpolate values for each item within the block.
The above can be tested by running this small test routine;
Private Sub ArrayTest()
Dim arr() As Double = {3, 8, 0, 0, 4, 2}
Call ArrayInterpolation(arr)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Debug.Print(String.Format("X={0}, Y={1}", i, arr(i)))
Next i
End Sub
Note that the code given assumes that the array index is equal to the X-coordinate. Also, the above routine only interpolates ... it does
not extrapolate (to see this, replace the array initialization value in the test Sub with
{0, 3, 8, 0, 0, 4, 2, 0}
.. the zeroes at the start and end of the array will not be replaced because there is only one known data value in each case).
Hope this helps.