How to change or redefine a (global?) variable from within a while loop

I am a beginner Julia user and perhaps I am overlooking something obvious but, how can I change a variable in the global scope from within a while loop?

using Distributions
#Constants
const Ropt = 100
const γ= 2
const NumSpecies = 50
const m = sort(rand(Uniform(10^2, 10^12), NumSpecies))

L = @. (m/(m'*Ropt) * exp(1-m/(m'*Ropt)))^γ 
L[L .<= 0.01] .= 0
L
#should L be a function? Would it look something like:
# function L(m,Ropt,γ)
# @. (m/(m'*Ropt) * exp(1-m/(m'*Ropt)))^γ
#L[L .<= 0.01] .= 0
#end

FoodWeb = zero(L)
FoodWeb[L .> rand.(Uniform(0, 1))] .= 1
FoodWeb

while (sum(FoodWeb, dims=(1))== 0) & (sum(FoodWeb, dims =(2))==0) #if both a column and a row has all zeros
  FoodWeb = zero(L) #I want to redo FoodWeb
  FoodWeb[L .> rand.(Uniform(0, 1))] .= 1
  return FoodWeb #here I want to stop remaking FoodWeb and place the new values of it into the previous global scope
end

I know that tuples are immutable and perhaps FoodWeb is a tuple?

Use the global keyword to assign to a global from a loop.

1 Like

I think you are confusing changing the value of a global variable with changing the contents of a container. The latter operation does not change the container, only the contents.

If the above is related to this and this question, you may be better off writing a function that just modifies an array, eg

function update_foodweb!(food_web, other, arguments)
    if something
        food_web[some_coordinates, :] = updated_stuff
    end
    food_web
end
1 Like

May be this condition is not exactly what you mean? This expression sum(FoodWeb, dims=(1)) evaluates to a 1×50 Array{Float64,2} and you are comparing with a scalar 0, the result is always false regardless. Perhaps you mean no whole column and row add up to zero? That’s, both vectors from sum(..,dims=1) and sum(..,dims=2) can have at most one zero? This is not guaranteed to happen!