function collision
% COLLISION -- simple collision model
  [P,V,M] = initialize_spheres;
  H=initialize_graphics(P);
  update_plot(H,P);
  c = 1.00;       % Elasticity
  delta = 0.005;  % Time step
  V(1)= 2;        % Initial velocity
  t=0.000;        % Simulation time
  for n=1:5000
      P(:)=P(:)+delta*V(:);
      for i=1:size(P)-1
         if (V(i) > 0 && P(i) > P(i+1)-1.9)
             V(i+1)=V(i)*M(i)*c/M(i+1);
             V(i)=0;
         end
      end
      update_plot(H,P);
      if (P(size(P)) > 13)
          return
      end
      t=t+delta;
  end
  
  close_graphics(H);
end

function [P,V,M] = initialize_spheres
%INITIALIZE SPHERES
  P = [-10;-2;0;2;4;6];
  V = [0;0;0;0;0;0];
  M = [1;1;1;1;1;1];

end
function [H] =initialize_graphics(P)
   clf
   shg
   set(gcf, 'color', 'white', 'numbertitle', 'off', 'name', 'Collision Model')
   axes('position', [0 0 1 1])
   axis([-10 10 -10 10])
   axis([-12.5 12.5 -12.5 12.5 0 25.0])
   axis square
   axis off
   view([0,0])
   n=size(P);
   for i = 1:n
      H.spheres(i)=line(5,5,5,'color',[1/4 1/4 1/4],'marker','.',...
      'markersize',80,'userdata',80);
   end
   
   drawnow
end
function update_plot(H,P)
  for i=1:size(P,1)
      set(H.spheres(i),'xdata',P(i),'ydata',0,'zdata',12);
  end
  drawnow
end
function close_graphics(H)
  clf
end
