Using increments in a for loop

I am trying to run a for loop in Julia using bounds for integration where fI

and r

are arrays of the same length. I know this is wrong, but this is the essence of what I want to do.

    a = zeros(1:length(fI))
    for i = 1:length(fI)
      a[i] = (fI[i+1] - fI[i])/(r[i+1] - r[i])
    end

      

How can I set n + 1 increments in Julia? No luck finding the answer elsewhere.

Just let me know if I can clarify something. I am still pretty new to this language.

+3


source to share


3 answers


I'm not really sure what you want to do, but it looks like you want to create a new variable based on the difference between elements in other variables. If this is your use case you can use diff

eg.



fI, r = rand(10), rand(10)
a = diff(fI) ./ diff(r)

      

+3


source


The ranges are indicated start:stepsize:end

. So the answer is for i = 1:(n+1):length(fI)

.



+2


source


Your code will work as for the last "i" you will access outside the array length

fI[i+1] = fI[length(fI)+1]


a = zeros(1:length(fI))
for i = 1:length(fI)
  a[i] = (fI[i+1] - fI[i])/(r[i+1] - r[i])
end

      

Perhaps you intend to use the following

n = length(fI) - 1
a = zeros(1:n)
for i = 1:n
  a[i] = (fI[i+1] - fI[i])/(r[i+1] - r[i])
end

      

+1


source







All Articles