FOR loops and range in Julia

23,904

Solution 1

Like StefanKarpinski noted, it is not the for loop (variable) that only takes integers, but the array index. You cannot access the 0.15th element of an array.

How about this:

x = range(0, stop=3, length=200)
y = zeros(length(x))

for i = 1:length(x)
  j = x[i]
  y[i] = j*cos(j^2)
end

Or even:

x = range(0, stop=3, length=200)
y = zeros(length(x))

for (i, j) in enumerate(x)
  y[i] = j * cos(j * j)
end

Solution 2

IMHO, the for loop takes more space without being clearer. Note sure what is considered "julianic", but in the python world I think most people would go for a list comprehension:

tic()
x = linspace(0, 3, 200)
y = [j*cos(j*j) for j in x]
toc()

elapsed time: 0.014455408 seconds

Even nicer to my eyes and faster is:

tic()
x = linspace(0, 3, 200)
y = x.*cos(x.^2)
toc()

elapsed time: 0.000600354 seconds

where the . in .* or .^ indicates you're applying the method/function element by element. Not sure why this is a faster. A Julia expert may want to help us in that.

Share:
23,904
Echetlaeus
Author by

Echetlaeus

"Mrs. Robinson, you're trying to seduce me. Aren't you?" The Graduate

Updated on March 09, 2021

Comments

  • Echetlaeus
    Echetlaeus about 3 years

    When I try to define range in a for loop when the range is less than 1 I get errors.

    For example the following code:

    i = linspace(0, 3, 200)
    graph = zeros(length(i), 1)
    
    for j in 0:0.015:3
        graph[j] = j*cos(j^2)
    end
    

    Reports the following error: ERROR: BoundsError()

    Why is that?