clear
% Fern Example
% Each row is a transformation (matrix + translation)
% [a b c d e f P]
% Caution: The last column has cumulative probabilities
% Actual probabilities for this fern are 0.85, 0.5, 0.5, 0.5
Data=[0.849  0.037 -0.037 0.849 0.075  0.1830 0.85; 
      0.197 -0.226  0.226 0.197 0.400  0.0490 0.90; 
     -0.15   0.283  0.260 0.237 0.575 -0.0840 0.95;
      0.00   0.00   0.00  0.16  0.500  0.0000 1.00];
[nrow ncol]=size(Data);
% Reshape data into transf matrix and translation vector
for j=1:nrow
    A(:,:,j)=reshape(Data(j,1:4),2,2)';
    B(:,:,j)=reshape(Data(j,5:6),2,1);
    P(:,j)=Data(j,7);
end
% Initialize plot
z=rand(1,2)';
Z=[z'];
p = plot(Z(1),Z(2),'.','EraseMode','none','MarkerSize',2); 
hold on
axis([0 1 0 1]);

% Begin Iterating with N iterations
N=10000;
for i=1:N
    q=rand;
    j=sum(P<q)+1;   %index of the function to be applied
    z = A(:,:,j)*z+B(:,:,j);
    Z=[Z ; z'];
    set(p,'XData',Z(1),'YData',Z(2))
    drawnow
end

hold off
plot(Z(:,1),Z(:,2),'.','markersize',3)
