%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         9. practice         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Nonlinear dynamics systems  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%         2016.11.16.         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%           Fractals          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Sierpinsky triangle

N=1000;
%fix points of the algorithm: the vertices of the triangle
P(1,1)=1;
P(1,2)=1;
P(2,1)=1000;
P(2,2)=1;
P(3,1)=500;
P(3,2)=860;

figure;
title('Sierpinski triangle');
xlim([0 N])
ylim([0 N])
iternum=1000000; %iteration number
C=zeros(iternum,2); %points of the triangle

c=P(randi([1,3]),:) %choose a fix point randomly
hold on;
% c - actual point - the reference (one of the fix points at first)
for i=2:iternum
    r = randi([1,3]); %choose a fix point randomly
    c = [(c(1)+P(r,1))/2, (c(2)+P(r,2))/2]; %the midpoint of the new point - fix point line
    C(i,:)=c; %store the new point 
    
    %plot step by step:
    %
   plot(c(:,1), c(:,2), '.', 'MarkerSize', 1);
   title('Sierpinski triangle');
   xlabel(['Iteration: ', num2str(i)]);
   drawnow;
    %}
end

 plot(C(:,1), C(:,2), '.', 'MarkerSize', 1);
 title('Sierpinski triangle');
 xlabel(['Iteration: ', num2str(iternum)]);