clear
clf

up = [0  1];
down = [0 -1];
right  = [1  0];
left  = [-1  0];

C1 = zeros(0,2); %curve 1
C2 = zeros(0,2); %curve 2
C3 = zeros(0,2); %curve 3
C4 = zeros(0,2); %curve 4

n = 10;

for i = 1:n
  rul = [C3 ; right ; C1 ; up ; C1 ; left ; C4];
  ldr = [C4 ; left ; C2 ; down ; C2 ; right ; C3];
  urd = [C1 ; up ; C3 ; right ; C3 ; down ; C2];
  dlu = [C2 ; down ; C4 ; left ; C4 ; up ; C1];

  C1 = rul;
  C2 = ldr;
  C3 = urd;
  C4 = dlu;

C1 = [0 0; cumsum(C1)];

%Hilbert curve
subplot(2,1,1);
plot(C1(:,1), C1(:,2),'LineWidth',2.25);
title(['n=',num2str(i)]);
axis equal, axis off

  
%length
subplot(2,1,2);
l = 2^i-1/2^i;
hold on
plot(i,l,'-o');
axis([0 n 0 2^n-1/2^n]);
xlabel('n iterations');
ylabel('length');
title(['n=',num2str(i),', length=',num2str(l)]);

%saveas(gcf, ['hilbert',sprintf('%03d',i),'.png'])
C1 = rul; %reset
pause();
end