% HW1 code solns: Matlab code to iterate a map on [0,1].    barnett 10/8/07
% Also compares *two* initial conditions on one graph, as in Compu Expt 1.4

% Define a map in the logistic family. Put your code here ...
a = 3.9;
f = @(x) a*x.*(1-x);

% ... and now to use the map:
N = 200;                   % number of iterations
x = zeros(1, N+1);         % 1-by-(N+1) sized list to store the history of x
y = zeros(1, N+1);
x(1) = 0.1;                % put starting value in first element of list
y(1) = 0.1 + 1e-15;        % slightly different IC

% Now write a loop of some kind to fill the rest of the x array up to x(N)
for n=1:N
  x(n+1) = f(x(n)); y(n+1) = f(y(n)); 
end

% Now comes plotting code that you don't need to change.
% If you filled x correctly then it will produce nice graphs ---------------

% graph function then add cobweb plot
xx = 0:0.004:1;
figure; plot(xx, f(xx), 'k-'); xlabel x; ylabel('f(x)'); title('cobweb plot');
axis([0 1 0 1]); hold on; plot([0 1], [0 1], 'g-');
for n=1:N
  plot([x(n) x(n) x(n+1)], [x(n) x(n+1) x(n+1)], '-');
  plot(x(n), x(n+1), '.', 'markersize', 10);
end

% plot iterations x_n and y_n vs n
figure; plot(0:N, x, '.-', 'markersize', 10); xlabel n; ylabel('x_n');
hold on; plot(0:N, y, 'r.-', 'markersize', 10);
axis([0 N 0 1]); title('iteration history');

% plot log of difference of x_n and y_n, vs n
figure; semilogy(0:N, abs(x-y), '.-', 'markersize', 10);
xlabel n; ylabel('|x_n-y_n|');
axis tight; title('log difference between two nearby orbits, vs n');

