MATLAB: Ode45 initial conditions iteration

initial conditionsiterationMATLABode45

I am trying to solve the following 2nd order differential equation, which works fine but I need to iterate the initial conditions, so everytime the ode is solved, the last values for q(:,1) and q(:,2) should be the new value for X and Y respectivley.
%solve_2nd_order_diff
duf=@(t,q)[q(2);f*w^2*cos(w*t)-(Cmech/J)*q(2)-(K1/J)*q(1)-(K3/J)*q(1)^3];
for r=1:length(Rad_speed)%freq of harmonic fluctuations, rad/s
[t,q]=ode45(duf,Time,[X Y]);
Max_values=max(q);
plot(t,q(:,1),'k')
xlabel('TIme,s')
ylabel('Relative Displacement, Rad')
grid
end

Best Answer

Like so
...
[X Y] = ...
for r=1:length(Rad_speed)%freq of harmonic fluctuations, rad/s
[t,q]=ode45(duf,Time,[X Y]);
[X Y] = [q(end,1) q(end,2)];
...