Photoniker
Photoniker

Reputation: 1

Math operation with an array but having problems with negative numbers

I got a few arrays and I want to do the following math operation:

For i As Integer = 10 To 100
    TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
    i = i + 1
Next

The problem is that sometimes mintranArray(i) has higher values than maxFirstArray(i) and maxSecondArray(i). So the program crashes. With Try Catch the program is not shutting down but I only get TransmissionArray() = Nothing.

Upvotes: 0

Views: 56

Answers (1)

RianBattle
RianBattle

Reputation: 898

Sounds like your TransmissionArray isn't being initialized properly. If you just Dim it like this:

Dim TransmissionArray() As Double

Then it will be Nothing. If you try to assign a value to it in this way, you will get an exception. Normally you can insert a number in the parenthesis (Dim TransmissionArray(10) As Double) and you would have an array of length 10 that you could immediately start assigning values to. But, if you don't know the length before hand, I can think of two options that would work:

Dim TransmissionArray() As Double
For i As Integer = 10 To 100
    ReDim Preserve TransmissionArray(i)     'This will increase the size of the array to the value of i, the Preserve keyword also saves the data already stored in the array
    TransmissionArray(i) = (maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i))
    'i = i + 1         'Commented this out...i is already incremented once each loop
Next

Or, switch to using a List(Of Double):

Dim TransmissionArray As New List(Of Double)
For i As Integer = 10 To 100
    TransmissionArray.Add((maxFirstArray(i) - mintranArray(i)) / (maxSecondArray(i) - mintranArray(i)))
    'i = i + 1         'Commented this out...i is already incremented once each loop
Next

Note that the second method would make TransmissionArray 10 items less than the other arrays, due to the fact you are starting the For loop counter at 10, and just adding items to the list.

Upvotes: 1

Related Questions