DifferentialEquations.jl Spring Mass Damper with variable force being applied

I am trying to do a simulation of a spring mass damper system where a variable force is constantly being applied at each integer time step. I want to see the mass’ position in a plot. This code seems to be a start but I’m stuck getting it to work.

force = rand(1000)
ts = collect(1:1000)
forces = LinearInterpolation(ts, force)

#x = u[1], v = u[2]
function smd(du, u, p, t)
c, k, m, F = p
du[1] = dx = u[2]
du[2] = dv = -(c/m)*u[2] - (k/m)*u[1] + F[t]
end

tspan = (1.0, ts[end]);

u0 = [0; 0]
p = [-10, 1, 10, forces]
prob = ODEProblem(smd, u0, tspan, p)
sol = solve(prob, Tsit5())

plot!(vecvec_to_mat(sol)[:, 1])

t will be a floating-point number, but you can only index with integers. Try floor(Int, t) if the data in F is sampled every second, or divide t by the sample rate if it is sampled at some other rate.


Edit, I see now that you use a LinearInterpolation (you haven’t said from which package), should you call this as a function F(t) instead?

In general, try to post code examples that actually run, without leaving anything out.