Free_ion
Free_ion

Reputation: 97

Plotting a function progressively with Julia

I'm having a hard time doing an animation with Julia.

I have a function sf(t)=t^(1/2) going from tmin=0 to tmax=40, and I don't understand how to show the solution progressively from tmin to tmax. I have tried multiple approaches using the Julia docs and tutos I found online but they almost all use predefined functions (mainly sin and cos). The error Julia returns with the code below is MethodError: no method matching getindex(::typeof(sf), ::Int64). I have two questions: Why is this error appearing? and Is Ithere a simpler way to create an animation than to access indices in a loop?

Thanks

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)

Upvotes: 1

Views: 518

Answers (1)

jling
jling

Reputation: 2311

IIRC the @animate or @gif macro expects a plot at the end of the loop, so you want to do something like this:

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

Upvotes: 2

Related Questions