Here's a simple implementation of the Bresenham line drawing algorithm in MATLAB:
main.m638 chars34 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.m72 chars6 lines
This will plot the line from (10,20) to (60,40) using the Bresenham algorithm.
gistlibby LogSnag