我是一名经济学专业的学生,慢慢地从MATLAB转到朱莉娅。
目前,我的问题是,我不知道如何声明(预先分配)一个向量,可以存储插值。
具体来说,当我执行一些接近:
function MyFunction(i)
# x, y vectors are some functions of 'i' defined here
f = LinearInterpolation(x,y,extrapolation_bc=Line())
return f
end
g = Vector{Function}(undef, N)
for i = 1:N
g[i] = MyFunction(i)
end我得到:
ERROR: LoadError: MethodError: Cannot `convert` an object of type Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}} to an object of type Function如果我而不是g=Vector{Function}(undef, N)声明g=zeros(N),我会得到类似的错误消息(以...Float64而不是... Function结尾)。
相反,当我宣布:
g = Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(N)我得到:
LoadError: MethodError: no method matching Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(::Int64) Closest candidates are: Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(::Any, !Matched::Any) where {T, N, ITPT, IT, ET}当我根本不声明"g“的时候,我就会得到:
ERROR: LoadError: UndefVarError: g not defined最后,当我宣布:
g = Vector{Any}(undef, N)代码可以工作,但我担心这可能会导致变量g的某些类型更改,从而降低性能敏感代码。
那么,在这种情况下,我应该如何声明g呢?
编辑:在现实中,我的问题有点复杂,更像以下所示:
function MyFunction(i)
# x, y vectors are some functions of 'i' defined here
f = LinearInterpolation(x,y,extrapolation_bc=Line())
h = is a T-vector of some functions of x,y
A = is some matrix depending on x,y
return h, A, f
end
h = Matrix{Function}(undef, T, N)
A = zeros(T,I,N)
g = Vector{Any}(undef, N)
for i = 1:N
h[:,i], A[:,:,i], g[i] = MyFunction(i)
end因此,当我使用理解或广播(如h, A, g = [MyFunction(i) for i in 1:N]或h, A, g = MyFunction.(1:N))时,如用户Benoit和DNS所建议的,我的函数的输出是3个元组,h,A,g,每个元组都包含{hi,Ai,gi}用于i=1,2,3。如果在LHS上只使用一个输出变量,即:MyOutput = [MyFunction(i) for i in 1:N]或MyOutput[i] = MyFunction.(1:N),则MyOutput成为一个包含N个元组条目的向量,每个元组都由{hi,Ai} i=1,2,3,.我敢打赌,有一种方法可以从MyOutput中的元组中提取这些元素,并将它们填充到h[:,i], A[:,:,i], g[i]中,但这似乎有点麻烦和缓慢。
发布于 2021-04-11 14:31:16
你可以
f = MyFunction(1)
g = Vector{typeof(f)}(undef, N)
g[1] = f
for i = 2:N
g[i] = MyFunction(i)
end我认为map也应该找出以下类型:
map(MyFunction, 1:N)https://stackoverflow.com/questions/67045776
复制相似问题