在 Julia 中循环更新数组,避免全局变量



根据 Julia 在 https://docs.julialang.org/en/v1/manual/performance-tips/index.html 中的性能提示,我们应该避免global变量。然后,如何在while循环中更新数组以避免global变量?例如,我重现了一个非常简单的情况,但我有更复杂的while循环情况,我必须始终在每次迭代时更新global变量:

i = 1 
x = 10
while i <10
global x = x+2
global i = i + 1
end

这是一个更复杂的例子,基于我的代码:

function consensus(p::Float64)        
prop=[1 rand() rand() rand() rand(); rand() 1 rand() rand() rand(); rand() rand()  1 rand() rand(); rand() rand() rand() 1 rand(); rand() rand() rand() rand() 1]
prop=Symmetric(prop)
thresh=sort(unique(prop))
g=map(i -> adjmat(proptotmemecl,thresh,i),1:length(thresh))
global listeclust=map(i -> comp(g,i),1:length(thresh))
global sizeclust=map(i -> nbcc(listeclust,i),1:length(thresh))
global sizesdelete=sort(filter(x-> x<=1000^p,unique(reduce(vcat,sizeclust))))
while length(sizesdelete)>0
ind2=map(i -> ind(listeclust,sizesdelete,i),1:length(thresh))
ind4=map(i-> closest(prop,i),ind2)
map(i -> agglom(g,ind2,ind4,i),1:length(thresh))
global listeclust=map(i -> comp(g,i),1:length(thresh))
global sizeclust=map(i -> nbcc(listeclust,i),1:length(thresh))
global sizesdelete=sort(filter(x-> x<= 1000^p,unique(reduce(vcat,sizeclust))))
end
listeclustuniq=unique(listeclust)
end

在这里,我创建了一个内部定义了数组的函数,其中while循环更新了其中的 3 个数组。adjmatcompnbccindclosestagglom是我之前在代码中创建的函数。我在这里想知道的是我如何更新 3 个数组listeclustsizeclustsizesdelete避免global定义,以提高性能。

您需要做的就是将所有这些放在一个函数中。

function f()
i=1...rest of code...
end
f()

将意味着最终范围内没有任何内容。

最新更新