%% Animation for a Saddle Node bifurcation

% Range of x
     xmin = 0;
     xmax = 10;

     x = xmin:0.1:xmax

% Value of k

     k = 2.5

% Range of r
     rmin = 0.0
     rmax = 1.5

% number of frames in the movie
     imax = 41

% Rage of dx/dt (here y=dx/dt)
     ymin = 0 ;
     ymax = 0.6;

%% Start of the loop for acquisition of the movie frames

for i = 1:imax

%calculate r value
     r = rmin + (i-1)*(rmax-rmin)/(imax-1)

%create string for labelling r
     strr = num2str(r);
     strt1 = ['r=' strr]; 
     strk = num2str(k);
     strt2 = ['k=' strk]; 


%calculate x/(1+x^2)
     y1 = x./(1 + x.^2)

% calculate r(1-x.k)
     y2 = r.*(1-x./k)

%plot f(x)
     plot(x,y1,'r');
     axis([xmin xmax ymin ymax])
     hold on
     plot(x,y2,'b');

%plot labels
     xlabel('x','FontSize',20)
     text(5,0.5,strt1,'FontSize',20)
     text(5,0.4,strt2,'FontSize',20)

%get movie frame
     h = gcf;
     M(i) = getframe(h,[5 5 480 380]);
     hold off

% end of loop
end

%play and save movie
     movie(M);
     movie2avi(M,'Budworm1','fps',0.5);