如何在 julia 中使用数组元素作为迭代器?

Fin*_*gan 3 math loops readability vector julia

我试图让我的 Julia 代码更容易理解(对物理学家来说),并认为如果我可以使用某种向量类型迭代器会很好。我试图将每个元素用作迭代器。到目前为止,我的解决方案是:

kcut=2
 = Array{Float64}(undef,3)
Ø = [0, 0, 0]

for [1] in -kcut:kcut, [2] in -kcut:kcut, [3] in -kcut:kcut
    if norm()^2 <= kcut^2 &&  != Ø
        println()
    end
end
println()
Run Code Online (Sandbox Code Playgroud)

这几乎完成了它应该做的事情。唯一的问题是一旦我完成了 for 循环,我的M被重新定义为它在循环中采用的最后一个配置,[2,2,2] 在这种情况下。当我迭代一个普通变量时,情况似乎并非如此

x=1
for x in 1:10
    println(x)
end
println(x)
Run Code Online (Sandbox Code Playgroud)

这告诉我循环后 x 仍然等于 1。如果可能,我希望有相同的行为。在我使用它进行迭代之前,有没有办法在不定义M 的情况下做到这一点?

编辑:我需要将M作为数组输出,以便我可以对其进行一些线性代数。

ffe*_*tte 5

您可以直接在M上进行迭代,例如像这样:

julia> using LinearAlgebra: norm
julia> kcut=2;
julia> Ø = [0, 0, 0];

julia> for  in Iterators.product(-kcut:kcut, -kcut:kcut, -kcut:kcut)
           if norm()^2 <= kcut^2 &&  != Ø
               #  is a Tuple now, which should be best in most cases.
               #
               # If you want arrays instead:
                = collect()

               println(, "\t", )
           end
       end
(0, 0, -2)      [0, 0, -2]
(-1, -1, -1)    [-1, -1, -1]
(0, -1, -1)     [0, -1, -1]
(1, -1, -1)     [1, -1, -1]
(-1, 0, -1)     [-1, 0, -1]
(0, 0, -1)      [0, 0, -1]
(1, 0, -1)      [1, 0, -1]
(-1, 1, -1)     [-1, 1, -1]
...

julia> println()
ERROR: UndefVarError:  not defined
Stacktrace:
 [1] top-level scope at REPL[5]:1
Run Code Online (Sandbox Code Playgroud)

这样,M只在for循环范围内定义。


要了解原始代码的行为,您必须对 Julia 内部执行的代码转换(“代码降低”)有基本的了解。特别是,for 循环按照迭代接口的规则进行替换

总而言之,一个片段如下:

M = [42]
for M[1] in -k:k
    println(M[1])
end
Run Code Online (Sandbox Code Playgroud)

行为方式与:

M = [42]
next = iterate(-k:k)
while next !== nothing
    M[1] = i
    println(M[1])
    next = iterate(iter, state)
end
Run Code Online (Sandbox Code Playgroud)

你看到的地方M 必须预先存在,这样才M[1]=i不会失败,并且没有理由为什么循环体内发生的事情在它之后不会持续存在。