存储由 for 循环生成的值。 JuMP/Julia
Store values generated by a for-loop. JuMP/Julia
令人惊奇的是,互联网上完全没有这个简单的问题(或类似问题)。或者我只是非常不擅长搜索。无论如何,我只是想将 for 循环生成的值存储在一个数组中并打印该数组。就这么简单。
在所有其他语言 Matlab、R、Python、Java 等上,这非常简单。但是在 Julia 中,我似乎缺少了一些东西。
using JuMP
# t = int64[] has also been tested
t = 0
for i in 1:5
vector[i]
println[vector]
end
我收到错误
ERROR: LoadError: BoundsError
我错过了什么?
您没有初始化 vector
,您应该在 Julia 1.0 中按如下方式调用方法 println
:
vector = Array{Int,1}(undef, 5)
for i in 1:5
vector[i] = i
println(vector[i])
end
或者,使用理解列表更快:
vector = [i for i in 1:5]
for i in 1:5
println(vector[i])
end
另一种使用push!
方法的可能性:
vector = []
for i in 1:5
push!(vector, i)
println(vector[i])
end
令人惊奇的是,互联网上完全没有这个简单的问题(或类似问题)。或者我只是非常不擅长搜索。无论如何,我只是想将 for 循环生成的值存储在一个数组中并打印该数组。就这么简单。
在所有其他语言 Matlab、R、Python、Java 等上,这非常简单。但是在 Julia 中,我似乎缺少了一些东西。
using JuMP
# t = int64[] has also been tested
t = 0
for i in 1:5
vector[i]
println[vector]
end
我收到错误
ERROR: LoadError: BoundsError
我错过了什么?
您没有初始化 vector
,您应该在 Julia 1.0 中按如下方式调用方法 println
:
vector = Array{Int,1}(undef, 5)
for i in 1:5
vector[i] = i
println(vector[i])
end
或者,使用理解列表更快:
vector = [i for i in 1:5]
for i in 1:5
println(vector[i])
end
另一种使用push!
方法的可能性:
vector = []
for i in 1:5
push!(vector, i)
println(vector[i])
end