Interpolate missing Data

淺唱寂寞╮ 提交于 2019-12-10 11:51:39

问题


I have data in excel , I need fill missing (blank) data, the input data is like:

row1 --> 1   2      3   blank   5   6   blank  blank   9   10

row2 --> 2   4   blank  blank   10  12    14   blank   18  blank

the VBA code must read each rows and fill them like :

row1 --> 1   2  3  4   5    6    7    8    9    10

row2 --> 2   4  6  8   10   12   14   16   18   20

is there clear solution to do this in VBA(excel)?


回答1:


Here is an Example for a mathematical solution:

  1. Generate x-values x (we need them as array for the next 2 steps)
  2. Calculate the slope m for the given row values
  3. Calculate the intercept c for the given row values
  4. Interpolate the missing values y with y = m * x + c

Example:

Option Explicit

Public Sub LinearInterpolateRowWise()
    Dim DataRange As Range
    Set DataRange = Worksheets("Sheet1").Range("A1:J3")

    Dim ArrX As Variant 'create an array of x-values
    ReDim ArrX(1 To 1, 1 To DataRange.Columns.Count)
    Dim c As Long
    For c = 1 To DataRange.Columns.Count
        ArrX(1, c) = c
    Next c

    Dim iRow As Long, iCol As Long
    For iRow = 1 To DataRange.Rows.Count 'loop row wise
        Dim Slope As Double 
        Slope = Application.WorksheetFunction.Slope(DataRange.Rows(iRow), ArrX)

        Dim Intercept As Double
        Intercept = Application.WorksheetFunction.Intercept(DataRange.Rows(iRow), ArrX)

        For iCol = 1 To DataRange.Columns.Count 'interpolate missing values
            If DataRange.Cells(iRow, iCol) = vbNullString Then
                DataRange.Cells(iRow, iCol) = Slope * iCol + Intercept 'y = m * x + c
            End If
        Next iCol
    Next iRow
End Sub

So assuming this source data

It interpolates like this

The following is a visualization of the interpolation of row 3:

So what happens is we calculate the linear equation through the given points (blue) and use it to calculate the missing point (orange).


This will even work for non linear original points (blue) like in the following Example.



来源:https://stackoverflow.com/questions/53554615/interpolate-missing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!