Modifying vectors in for loop doesn't work

I would like to have a function which would generate vectors of the same length and average them together into a single vector. I can’t quite understand why the following example wouldn’t work (the value of vector remains the same as initially assigned in the second line):

function f(N)
     vector = rand(3)
     for n in 2:N
          v = rand(3)
          (vector).+v
          display(vector)
     end
     (vector)./N
     return vector
end

display(f(5))

you do calculations on vector but don’t reassign it back.
E.g. in line 5 you probably want

vector = vector .+ v

or equivalently

vector .+= v

Same goes for line 8

5 Likes