
% generate dragon curve
function output = dragon_curve(levels, angle, starting_X, starting_Y)

% x and y are arrays that hold the (x,y) values of each point in
% the dragon curve. For example a point P1 with coordinates (x1,y1)
% can be found in x(1), y(1).
% The length of x and y on one iteration is 3 (because 2 connected line
% segments, on two iterations it's 5 (because 4 connected line segments)
% and so on. The lengths are always the same.
x = starting_X;
y = starting_Y;

for i = 1:levels
    
    % flip vector to start have points in order
    flippedX = flip(x);
    flippedY = flip(y);
    
    % size of x and y
    sizeX = size(x,2);
    sizeY = size(y,2);
    
    % set new starting points
    a = x(sizeX);
    b = y(sizeY);
    
    % find the angle of the next segment with repsect to its
    % neighboring segment
    [theta, r] = cartesianToPolar(flippedX - a, flippedY - b);
    [rx, ry] = polarToCartesian(theta + angle, r);
    
    % reset to the correct length/orientation
    rx = rx + a;
    ry = ry + b;
    
    % add to the already existing points
    sizeRx = size(rx, 2);
    sizeRy = size(ry, 2);
    x = [x rx(2:sizeRx)];
    y = [y ry(2:sizeRy)];
    
%     saveas(gcf, ['dragon_curve_', sprintf('%03d', i), '.png']);
    
    output = plot(x, y, 'b', 'LineWidth', 3);
    hold on;
    pause(0.5)
    axis equal
    
end

% flips a vector
% e.g. A = [1 2 3] then flip(A) = [3 2 1]
% e.g. B = [1;2, 3;4] then flip(B) = [3;4, 1;2]
function y = flip(vector)

sizeV = size(vector);
sizeX = sizeV(1);
sizeY = sizeV(2);
y = zeros(sizeX, sizeY);
for i = 1:sizeX
    for j = 1:sizeY
        y(i, sizeY - j + 1) = vector(i, j);
    end
end

% transform cartesian to polar coordinates in 2D 
function [theta,r] = cartesianToPolar(x,y)
theta = atan2d(y,x);
r = sqrt(x.^2 + y.^2);

% transform polar to cartesian coordinates in 2D
function [x,y] = polarToCartesian(theta,r)
x = r.*cosd(theta);
y = r.*sind(theta);

% Referred to code from: http://www.mathworks.com/matlabcentral/fileexchange/11069-dragon-curve--aka-jurassic-park-fractal-/content/html/dragon_curve.html
% None of the above is copied code, it is all my own, the main prcodeure is similar.
