% Matlab code for a beautiful Fractal Fern
% ... created from the IFS defined in Table III.3, pg.86 of the handout
% just type "Fern" in the Matlab command window to run it

clf;
clear;

% recall, the transformations are of the form A*[x,y]+t
% and, there are four such transformations ...
A1=[0.14 0.01 ; 0 0.51];
A2=[0.43 0.52 ; -0.45 0.5];
A3=[0.45 -0.49 ; 0.47 0.47];
A4=[0.49 0 ; 0 0.51];
b1=[-0.08 ; -1.31];
b2=[1.49 ; -0.75];
b3=[-1.62 ; -0.74];
b4=[0.02 ; 1.62];
% here are the probabilities with which each transformation is applied
% notice that p1+p2+p3+p4=1
p = [0.1 0.35 0.35 0.2];

% the initial point
x(1)=0;
y(1)=0;
% but, let's write the (x,y) points as a vector, v
v=[0;0]; % here is the intial point

iterations=475000; %the number of iterations
for n=2:iterations
    % choose a random number, k, between 0 and 1
    k=rand;
    % depending on your random number ...
    % do one of the four transformations to get a new point
    if k<p(1)
        v=A1*v+b1;
    elseif k<p(1)+p(2)
        v=A2*v+b2;
    elseif k<p(1)+p(2)+p(3)
        v=A3*v+b3;
    elseif k<p(1)+p(2)+p(3)+p(4)
        v=A4*v+b4;
    end
    % now, go back and define your (x,y) point as elements of the vector v
    x(n)=v(1);
    y(n)=v(2);
end
%now, let's plot all those (x,y) points that we just computed!
opengl software %this is a fix to ensure that Matlab won't crash :)
hold off
plot(x,y,'.','Color',[1 0.5 0.25],'Markersize',1)
% uncomment the next two lines to see the initial point in red
% hold on
% plot(x(1),y(1),'r*','Markersize',4)
% axis('square','off');
set(gcf, 'color', 'white');
