Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOR loops and range in Julia

Tags:

julia

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?

like image 305
Echetlaeus Avatar asked Nov 22 '14 20:11

Echetlaeus


People also ask

Does Julia have for loops?

As in other languages, Julia supports two basic constructs for repeated evaluation: while and for loops. Loops are useful to repeat the same computation multiple times with different values. A typical example is performing operations on array elements.

How do you use loops in Julia?

For loops are used to iterate over a set of values and perform a set of operations that are given in the body of the loop. For loops are used for sequential traversal. In Julia, there is no C style for loop, i.e., for (i = 0; i < n; i++). There is a "for in" loop which is similar to for each loop in other languages.

ARE FOR loops in Julia fast?

Loops are just as fast in Julia as they are in Fortran, and a well-written loop is often the single fastest way to implement an algorithm.

How do you stop a while loop in Julia?

'break' keyword in Julia is used to exit from a loop immediately. Whenever the break keyword is executed, the compiler immediately stops iterating over further values and sends the execution pointer out of the loop.


2 Answers

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
like image 155
user4235730 Avatar answered Nov 23 '22 23:11

user4235730


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.

like image 20
cd98 Avatar answered Nov 24 '22 01:11

cd98