Search code examples
juliajulia-jumpjulia-studio

How can I mange the index of the loop in julia?


It is the section of the Genetic algorithm that is coding in Julia. the code was wrote as follow:

popc= [individual(rand(0:1,nvar),[]) for i in 1:nc/4,j in 1:2];
for k=1:nc/4
    #select firdt parent
    i1=rand(1:npop);
    p1=pop[i1];
    #select second parent
    i2=rand(1:npop);
    if i1==i2
        i2=rand(1:npop);
    end
    p2=pop[i2]
    #apply crossover
    m=singlepointcrossover(p1.position,p2.position);
    append!(popc[k,1].position, m[1]);
    append!(popc[k,2].position, m[2]);
end
function singlepointcrossover(x1,x2)

    nvar=length(x1);

    cutpoint=rand(1:nvar-1);

    y1=append!(x1[1:cutpoint],x2[cutpoint+1:end]);

    y2=append!(x2[1:cutpoint],x1[cutpoint+1:end]);

    return y1,y2
end

but it has this error. would you pleas help me?. why is it happened?

ArgumentError: invalid index: 1.0
getindex(::Array{individual,2}, ::Float64, ::Int64) at abstractarray.jl:883
macro expansion at GA.juliarc.jl:87 [inlined]
anonymous at <missing>:?
include_string(::String, ::String) at loading.jl:522
include_string(::String, ::String, ::Int64) at eval.jl:30
include_string(::Module, ::String, ::String, ::Int64, ::Vararg{Int64,N} where N) at eval.jl:34
(::Atom.##102#107{String,Int64,String})() at eval.jl:82
withpath(::Atom.##102#107{String,Int64,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
hideprompt(::Atom.##101#106{String,Int64,String}) at repl.jl:67
macro expansion at eval.jl:80 [inlined]
(::Atom.##100#105{Dict{String,Any}})() at task.jl:80

Solution

  • The problem is / operator gives floating-point results for integer arguments and floating point results cannot be used for indexing an Array. You can index an Array with an Integer.

    /(x, y)

    Right division operator: multiplication of x by the inverse of y on the right. Gives floating-point results for integer arguments.

    for k=1:nc/4
    

    1:nc/4 will create a Float64 range and k, a Float64, is later used in indexing in your code at append!(popc[k,1].position, m[1]);. You should, therefore, make k an Integer.

    If nc is an integer, you should use Euclidean division with div(nc, 4) or simply nc ÷ 4, or bit shift operators nc >> 2 and nc >>> 2 (for Euclidean division by 2^n you should shift by n). They will all give integer results for integer arguments.

    If nc itself is a floating-point number, you should probably use one of the options pointed out by @Colin T Bowers.


    popc= [individual(rand(0:1,nvar),[]) for i in 1:nc/4,j in 1:2];
    

    You do not have an error on the first line, since you do not use i for indexing here. It is still better to replace nc/4 with one of the options I listed above.