# DifferentialEquations.jl Spring Mass Damper with variable force being applied

**URL:** <https://discourse.julialang.org/t/differentialequations-jl-spring-mass-damper-with-variable-force-being-applied/117209>\
**Category:** General Usage\
**Created:** [July 19, 2024, 3:01am UTC](https://discourse.julialang.org/t/differentialequations-jl-spring-mass-damper-with-variable-force-being-applied/117209 "2024-07-19T03:01:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bryaan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bryaan/32/36858_2.png) [@bryaan](https://discourse.julialang.org/u/bryaan)\
**Post date:** [July 19, 2024, 3:01am UTC](https://discourse.julialang.org/t/differentialequations-jl-spring-mass-damper-with-variable-force-being-applied/117209/1 "2024-07-19T03:01:23Z")

</div>

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])

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [July 19, 2024, 4:10am UTC](https://discourse.julialang.org/t/differentialequations-jl-spring-mass-damper-with-variable-force-being-applied/117209/2 "2024-07-19T04:10:31Z")

</div>

> [@bryaan](#):
>
> F[t]

`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.
