MATLAB: Help to Optimize a parameter to meet constraints

fminconmassodeode45optimizationparamaterspring

I am modelling two masses connected by a spring with an initial displacement from one another. I am using ode45 to solve four 1st order ODEs. Could someone help me to find a way to evaluate a value for the spring stiffness that would cause the (position of mass 2 – position of mass 1 = 0 at a given time )
I have tried following a few tutorials on here but cannot understand and apply the condition to my problem.

Best Answer

min: (Position of mass 2(t_given) - Position of mass 1(t_given))^2
under the constraints of your 4 ordinary differential equations.
Structure of your program should look somewhat like:
function main
k_initial = ...; % Give initial guess for the spring stiffness you search for
k_sol = fminsearch(@fun_opt,k_initial) % call optimizer
end
function obj = fun_opt(k)
t_given = ...; % Specify time at which positions of the masses should coincide
tspan = [0 t_given]; % define interval of integration
x0 = [x01 x02 x03 x04]; % specify Initial conditions for the differential variables
[t, xsol] = ode15s(@(t,x)fun_diff(t,x,k),tspan,x0); % call integrator
obj = (xsol(end,1)-xsol(end,3))^2 % Evaluate objective function (this assumes that position of mass 1 is stored in x(1), position of mass 2 is stored in x(3))
end
function dx = fun_diff(t,x,k)
%Calculate time derivatives dx1,dx2,dx3,dx4
dx = [dx1;dx2;dx3,dx4]; % return vector of derivatives
end