Echetlaeus
Echetlaeus

Reputation: 343

FOR loops and range in 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?

Upvotes: 8

Views: 34099

Answers (2)

user4235730
user4235730

Reputation: 2619

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

Upvotes: 14

cd98
cd98

Reputation: 3532

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.

Upvotes: 6

Related Questions