【问题标题】:Plotting a function progressively with Julia使用 Julia 逐步绘​​制函数
【发布时间】:2021-05-10 00:17:25
【问题描述】:

我很难和 Julia 一起做动画。

我有一个函数 sf(t)=t^(1/2) 从 tmin=0 到 tmax=40,我不明白如何从 tmin 到 tmax 逐步显示解决方案。我使用网上找到的 Julia 文档和教程尝试了多种方法,但它们几乎都使用预定义的函数(主要是 sin 和 cos)。 Julia 使用以下代码返回的错误是 MethodError: no method matching getindex(::typeof(sf), ::Int64)。我有两个问题:为什么会出现这个错误?有没有比循环访问索引更简单的方法来创建动画?

谢谢

using Plots
tmin=0
tmax=40
tvec= range(tmin,tmax,length=100) 

# I define the function here, but I'm not sure this is really needed
function sf(t) 
    t^(1/2)
end

# I create an "empty" plot to use it in animation
p=plot(sf,0)

# To create the animation, I do a loop over all t's present in tvec
anim = @animate for i ∈ 0:length(tvec)-1
    push!(p,tvec(i),sf(i))
    frame(anim)
end

# And finally I (try to) display the result
gif(anim,"scale_factor.gif",fps=30)

【问题讨论】:

    标签: julia


    【解决方案1】:

    IIRC @animate@gif 宏在循环结束时需要一个绘图,所以你想做这样的事情:

    anim = @animate for i ∈ eachindex(tvec)
               plot(sf, tvec[begin:i])
           end
    gif(anim,"scale_factor.gif",fps=30)
    

    【讨论】:

    • 注意几点,可以100%push!()成情节,一般是这样更新的。此外,根据原始代码,值得一提的是 Julia 使用基于 1 的索引,请记住这一点以供将来的代码使用。
    • julia> p = plot(sf, 0:1) julia> push!(p, 0.5, 0.8) ([0.0, 1.0, 0.5], [0.0, 1.0, 0.8]) julia> p Error showing value of type Plots.Plot{Plots.GRBackend}: 也许push!() 可以工作,但它似乎完全不稳定(而且令人困惑?)
    • 感谢您的回答和评论,它现在运行良好。但是,在 for 循环中调用新图不是比在外部创建它并使用推送更新它更消耗资源吗?
    • 制作“情节”的内部表示非常便宜,重要的部分是使用 GR 将其渲染出来,您必须为每个“帧”做任何事情,没有更新的魔力渲染到位
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多