function myfern(n)
% MYFERN : plot a fractal fern
%
% myfern(n) plots n points.  Default is n = 1000

if nargin < 1
    n = 1000;
end;

p  = [ .85  .92  .99  1.00];
A1 = [ .85  .04; -.04  .85];  b1 = [0; 1.6];
A2 = [ .20 -.26;  .23  .22];  b2 = [0; 1.6];
A3 = [-.15  .28;  .26  .24];  b3 = [0; .44];
A4 = [  0    0 ;   0   .16];

x  = [.5 ; .5];        % start x at the base of the stem

figure; 
plot(x(1),x(2),'g.');

hold on;
for i = 1:n
   r = rand;
   if r < p(1)
      x = A1*x + b1;    % 85% of the time: move x up toward the tip
   elseif r < p(2)
      x = A2*x + b2;    %  7% of the time: move x into the lower right frond
   elseif r < p(3)
      x = A3*x + b3;    %  7% of the time: move x into the lower left frond
   else
      x = A4*x;         %  1% of the time: move x onto the stem
   end
   plot(x(1),x(2),'g.','markersize',5);
   drawnow
end