Xentro
Xentro

Reputation: 45

Julia loop with variable bound gives "invalid index"

In julia when I do:

N=1000;
for i = 2:N,
    alpham[i] = 0.1 * (V[i-1]+40.) / (1. - exp(-(V[i-1]+40.)/10.));
end

with alpham and V vectors of lenght 1000. I get the error "ArgumentError: invalid index: 1.0". However, if I do:

for i = 2:1000,

it does work. Is there any reason why the previous one doesn't or is there any way I can still use N in my for loop? Am I doing something wrong?

Thanks in advance, Xentro

Upvotes: 0

Views: 4760

Answers (1)

Michael K. Borregaard
Michael K. Borregaard

Reputation: 8044

The ArgumentError tells you that you're indexing with a Float64, doing that isn't defined in Julia. In your Minimally Working Example (MWE) you initialize N as 1000 (an Int) so the MWE actually doesn't reproduce the error, but in your comment you note that in your original code you get N as floor(x), which returns a float. To get an Int you need floor(Int, x).

There are also some syntax issues: you shouldn't have a , after for i = 2:1000, and it is usually not necessary to end statements with ;.

Note that you should make sure that the MWE can run purely by copy-pasting the code in a REPL (i.e. so variables need to be initialized, alpham, V = ones(1000), ones(1000)). Run it yourself before posting to ensure it reproduces the error you report, and to catch any syntax errors.

Upvotes: 12

Related Questions