MATLAB: How to solve an equation of motion with the ode solver when the spring constant is dependent on the position of the solution of the equation of motion

beerequation of motionodespring constant

I have the following equation of motion of a mass m and a position dependable springconstant k(x):
m*x''(t)+k(x)*x(t)=0
Where k(x) is the spring constant that is dependable on the position of x at a the time step that x is solved.
I can solve this with the Forward Euler Method by substituting the position x(n) at time step n into k(x(n)) and calculating the next position x(n+1) ect.
But with the ode solver it seems I can't do this, because the solver continues from the first time step to the last without letting me do anything in between.
Now I am new to matlab and still a student, so i don't have a lot of experience with Matlab. I hope this is a simple problem that a more experienced Matlab user can help me to solve this problem.
Thanks,
Maarten

Best Answer

There is absolutely no problem in using MATLAB's ODE solvers to solve a problem like this. Say for example
k(x) = 1+x^2
Then you can solve your ODE
m*x''+(1+x^2)*x=0
just like this:
ode45(@(t,x) [x(2); -x(1)*(1 + x(1)^2) ] ,[ 0 10 ] ,[ 1 0 ])
Related Question