4

I am trying to generate a population for a GA. I used a 2d array to help generate a population. First the user will enter the population size and then the chromosome length, into a UserForm.

My variables:

Dim Generation As Integer
Dim Chromolength As Integer
Dim varchromolength As Integer
Dim Poparr() As Integer

Then I fetch the values from the UserForm:

PopSize = PopulationSize.value
aVariables = AOV.value          'assign userform value entered to this variable
varchromolength = Chromolengthentered.value    'assign userform value entered to this   variable
Chromolength = varchromolength * aVariables   'Chromosome length equals the length of     each varaible chromosome combined

The coding where the error occurs:

For i = 1 To PopSize           
    For j = 1 To Chromolength       
        If Rnd < 0.5 Then           
            Poparr(i, j) = 0   'assign o to gene
        Else
            Poparr(i, j) = 1   'assign 1 to gene     
        End If
    Next j
Next i

1 Answer 1

5

Based on your code, you never assign the dimensions of the array. To do so, insert this line before your for loop, after setting the values of PopSize and ChromoLength.

Redim Poparr(1 to PopSize, 1 to ChromoLength)

Unnecessary details: You could just run Redim Poparr(PopSize, ChromoLength) but that would result in arrays that were 0 to Popsize etc... unless you add Option Base 1 to the top of your module. The default base for arrays is 0. I feel that it is better to explicitly indicate the lowerbound and upperbound of your array because the default can be 0 or 1 depending on the context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.