clear
clf

%% INTIAL CONDITIONS

a=1 %intial branch length
r=0.7 %ratio that determines decreasing branch lengths
theta=60 %note theta is the half angle between the branch pairs
iter=10 %number of iterations
T=[0;1]; %trunk position

%% ROTATION MATRIX

L=[r*cosd(theta) , -r*sind(theta) ; r*sind(theta) , r*cosd(theta)];
R=[r*cosd(theta) , r*sind(theta) ; -r*sind(theta) , r*cosd(theta)];

%% DEFINING FIRST ARRAY

A2=zeros(2,1)
A2(2,1)=1; %this is a 2 by 1 array

plot([0,A2(1,1)],[0,A2(2,1)],'Color',[0.65 0.5 0.3],'Linewidth',(iter+15)/3) %plotting thick brown trunk
hold on
axis ([-2 2 0 4])
title (sprintf('ANGLE = %d', theta))
hold on
pause(0.5)

%% PLOTTING THE FIRST TWO BRANCHES

A1=zeros(2,2); %create second array
A1(:,1)=L*A2(:,1)+T;
A1(:,2)=R*A2(:,1)+T;

%using the first array to plot to the second array points
plot([A2(1,1),A1(1,1)],[A2(2,1),A1(2,1)],'Color',[0.65 0.5 0.3],'Linewidth',(iter+1)/3)
hold on
axis ([-2 2 0 4])
plot([A2(1,1),A1(1,2)],[A2(2,1),A1(2,2)],'Color',[0.65 0.5 0.3],'Linewidth',(iter+1)/3)
hold on
pause(0.5)


A2=zeros(2,length(A1)*2) %altering the first array

%% PLOTTING THE REST OF THE BRANCHES

for i=1:iter
    for j=1:2^(i+1) %for the entire array
        if j<=(2^(i+1))/2 %if "on the left" of the array
            A2(:,j)=L*A1(:,j) + T; %multiply with the left rotation matrix
        else %if "on the right" of the array
            A2(:,j)=R*A1(:,j-((2^(i+1))/2)) + T; %multiply with the right rotation matrix
        end
    end
    for k=2:2:2^(i+1) %plotting the branches by a pair to each point on the intial array
        plot([A1(1,k/2),A2(1,k-1)],[A1(2,k/2),A2(2,k-1)],'Color',[0.65 0.5 0.3],'Linewidth',((iter+1-i)/3)) %plot left branch
        hold on
        plot([A1(1,k/2),A2(1,k)],[A1(2,k/2),A2(2,k)],'Color',[0.65 0.5 0.3],'Linewidth',((iter+1-i)/3)) %plot right branch
        hold on
    end
    pause(0.5)
    A1=A2; %reset first array
    A2=zeros(2, length(A1)*2); %make new blank second array
    
    
end

%% PLOT THE LEAVES

plot(A1(1,:),A1(2,:),'d','Color',[0 1 0],'Markersize',iter*(5/6))
hold off
