FOR loops and range in Julia

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 = linspace(0, 3, 200)
y = zeros(length(x))

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

Or even:

x = linspace(0, 3, 200)
y = zeros(length(x))

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

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.

Tags:

Julia