make bresenham algorithm from scratch in matlab

Here is an implementation of the Bresenham Algorithm in MATLAB for drawing a line between two points (x1,y1) and (x2,y2).

main.m
function [x,y] = bresenham(x1,y1,x2,y2)
% Bresenham's line algorithm
% https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm

dx = abs(x2 - x1);
dy = abs(y2 - y1);

slope = dy > dx;

if slope
    [x1,y1] = swap(x1,y1);
    [x2,y2] = swap(x2,y2);
    [dx,dy] = swap(dx,dy);
end

if x1 > x2
    [x1,x2] = swap(x1,x2);
    [y1,y2] = swap(y1,y2);
end

% Initialize error
error = mfloor(dx/2);
y = y1;

if y1 < y2
    ystep = 1;
else
    ystep = -1;
end

% Iterate through x values
for x = x1:x2
    if slope
        plot(y,x);
    else
        plot(x,y);
    end
    error = error - dy;
    if error < 0
        y = y + ystep;
        error = error + dx;
    end
end

% Helper function for swapping values
function [a,b] = swap(a,b)
    temp = a;
    a = b;
    b = temp;
end

end
782 chars
53 lines

To test the algorithm, call it with the starting and ending point coordinates:

main.m
x1 = 2;
y1 = 3;
x2 = 9;
y2 = 8;

[x,y] = bresenham(x1,y1,x2,y2);
65 chars
7 lines

This will return arrays of x and y coordinates that you can use to plot the line:

main.m
plot(x,y)
10 chars
2 lines

This will draw a line between the points (2,3) and (9,8) using the Bresenham Algorithm.

gistlibby LogSnag