I have a code for bilinear interpolation in VBA, but now I need an inverse bilinear interpolation - I know the z point and y point and I need to get x point. I am brand new to VBA and have no idea how to do this. Could you tell me how to change my code to do it? Thank you
Code:
Public Function GetBilinearInterpolation(xRange As Range, yRange As Range, zRange As Range, xcoord As Double, ycoord As Double) As Double
Dim xAxis() As Variant
Dim yAxis() As Variant
Dim zSurface() As Variant
xAxis = xRange
yAxis = Application.Transpose(yRange)
zSurface = zRange
'first find 4 neighbouring points
nx = UBound(xAxis, 1)
ny = UBound(yAxis, 1)
Dim lx As Single 'index of x coordinate of adjacent grid point to left of P
Dim ux As Single 'index of x coordinate of adjacent grid point to right of P
GetNeigbourIndices xAxis, xcoord, lx, ux
Dim ly As Single 'index of y coordinate of adjacent grid point below P
Dim uy As Single 'index of y coordinate of adjacent grid point above P
GetNeigbourIndices yAxis, ycoord, ly, uy
fQ11 = zSurface(lx, ly)
fQ21 = zSurface(ux, ly)
fQ12 = zSurface(lx, uy)
fQ22 = zSurface(ux, uy)
'if point exactly found on a node do not interpolate
If ((lx = ux) And (ly = uy)) Then
GetBilinearInterpolation = fQ11
Exit Function
End If
x = xcoord
y = ycoord
x1 = xAxis(lx, 1)
x2 = xAxis(ux, 1)
y1 = yAxis(ly, 1)
y2 = yAxis(uy, 1)
'if xcoord lies exactly on an xAxis node do linear interpolation
If (lx = ux) Then
GetBilinearInterpolation = fQ11 + (fQ12 - fQ11) * (y - y1) / (y2 - y1)
Exit Function
End If
If (ly = uy) Then
GetBilinearInterpolation = fQ11 + (fQ22 - fQ11) * (x - x1) / (x2 - x1)
Exit Function
End If
fxy = fQ11 * (x2 - x) * (y2 - y)
fxy = fxy + fQ21 * (x - x1) * (y2 - y)
fxy = fxy + fQ12 * (x2 - x) * (y - y1)
fxy = fxy + fQ22 * (x - x1) * (y - y1)
fxy = fxy / ((x2 - x1) * (y2 - y1))
GetBilinearInterpolation = fxy
End Function
Public Sub GetNeigbourIndices(inArr As Variant, x As Double, ByRef lowerX As Single, ByRef upperX As Single)
N = UBound(inArr, 1)
If x <= inArr(1, 1) Then
lowerX = 1
upperX = 1
ElseIf x >= inArr(N, 1) Then
lowerX = N
upperX = N
Else
For I = 2 To N
If x < inArr(I, 1) Then
lowerX = I - 1
upperX = I
Exit For
ElseIf x = inArr(I, 1) Then
lowerX = I
upperX = I
Exit For
End If
Next I
End If
End Sub