bresenham algo in matlab

Here's a simple implementation of the Bresenham line drawing algorithm in MATLAB:

main.m
function [x, y] = bresenham(x1, y1, x2, y2)
    dx = abs(x2 - x1);
    dy = abs(y2 - y1);
    sx = sign(x2 - x1);
    sy = sign(y2 - y1);
    x = x1;
    y = y1;
    swap = false;
    if dy > dx
        temp = dx;
        dx = dy;
        dy = temp;
        swap = true;
    end
    e = 2 * dy - dx;
    for i = 1:dx
        plot(x, y, 'b.');
        while e >= 0
            if swap
                x = x + sx;
            else
                y = y + sy;
            end
            e = e - 2 * dx;
        end
        if swap
            y = y + sy;
        else
            x = x + sx;
        end
        e = e + 2 * dy;
    end
end
638 chars
34 lines

The function takes four input arguments, the x and y coordinates of the starting and ending points of the line. The Bresenham algorithm works by incrementally plotting pixels that are closest to the true line path. It avoids floating-point arithmetic and uses only integer additions, subtractions, and multiplications.

The sign function is used to determine the sign of the increments in x and y. The abs function is used to ensure that dx and dy are positive. The swap variable is used to check whether we have swapped the x and y coordinates or not.

The plot function is used to plot each pixel that lies on the line. Once the loop is complete, the function returns a set of x and y coordinates that form the line.

To use this function, simply call it with the starting and ending points of your line as arguments:

main.m
x1 = 10;
y1 = 20;
x2 = 60;
y2 = 40;
[x, y] = bresenham(x1, y1, x2, y2);
72 chars
6 lines

This will plot the line from (10,20) to (60,40) using the Bresenham algorithm.

gistlibby LogSnag