I have a for loop that is working as intended. I iterate over an array of values and replace bad values (-99999) with the closest good value (if the bad value is on either end of the array) or the average of the two surrounding values (if the bad value is in the middle of the array). However, these nested loops smelled to me and I am looking for any suggested means of optimizing this (in terms of readability or performance).
I could access or remove the bad values using Dim badValues = MeasuredValues.Where(Function(x) x = -99999)
but I'm not sure how I can keep track of the indexes for calculating the replacement value when using .Where
. I'm no vb.net expert.
For index = 0 To MeasuredValues.Count - 1
If MeasuredValues(index) = -99999 Then
Dim nextGoodValue = -99999
Dim previousGoodValue = -99999
Dim replacementValue = -99999
For j = index To MeasuredValues.Count - 1
If MeasuredValues(j) <> -99999 Then
nextGoodValue = MeasuredValues(j)
Exit For
End If
Next
For k = index To 0 Step -1
If MeasuredValues(k) <> -99999 Then
previousGoodValue = MeasuredValues(k)
Exit For
End If
Next
If previousGoodValue = -99999 Then
replacementValue = nextGoodValue
ElseIf nextGoodValue = -99999 Then
replacementValue = previousGoodValue
Else
replacementValue = (nextGoodValue + previousGoodValue) / 2
End If
MeasuredValues(index) = replacementValue
End If
Next
Thanks for your time, please let me know if you need more info or have any questions.