Problem with object update and variable scope inside for loop


#1

Hi,

I am a new Julia user, and in programming in general, and I would like some help to understand why updates in the array “pressure” in the code below does not carry over after the for loop.

Note that a similar code in python seems to be working fine. Please let me know what I am missing and, perhaps, a way to get it right.

Thank you in advance for you help and time,

function Create_Fault_List(s, fault_list_size)
  pressure=zeros(1,s)

  fault=[] 
  for i=1:fault_list_size
    push!(fault,Create_Pressure_Type(pressure))
  end #close fo loop

  return fault

end

type Create_Pressure_Type
  pressure::Array{Float64}  
end

#List with 5 elements
s=5 #size of the pressure vector
fault_list_size = 10 # size of the fault list
fault=Create_Fault_List(s, fault_list_size)

index=3 #index to update in the vector pressure
for k=1:length(fault)
  #I would like to update the index element of the array pressure
  fault[k].pressure[index]=k

  #It seems to work, as you can see here
  println("pressure vector inside the loop ",fault[k].pressure)
end

println("\n")

#However here the pressure array has only the last element
for i=1:length(fault)
  println("pressure vector outside the loop=", fault[i].pressure)
end


#2

You put the same array into every element…

push!(fault,Create_Pressure_Type(copy(pressure)))

if you want to use different arrays all with the same value.


#3

thank you for reply. It worked fine now !