Daily Archives: June 16, 2011

draw line segments in matlab

After spending some effort searching online, I found one solution:

r = 5;
x1 = linspace(pos.cx – r, pos.cx + r);
y1 = linspace(pos.cy, pos.cy);

x2 = linspace(pos.cx, pos.cx);
y2 = linspace(pos.cy – r, pos.cy + r);

index1 = sub2ind(size(im), round(y1), round(x1));
index2 = sub2ind(size(im), round(y2), round(x2));
im(index1) = 127; % set the valudes to 127 for display
im(index2) = 127; % set the valudes to 127 for display

The above code snippet is used to draw a cross on an image or matrix. Because of over sampling, the line drawn is without aliasing artifacts. For drawing lines on figures, there exists an easier solution, just use function ‘line’. For example:

line(rect(1,:), rect(2,:),’Color’,’r’,’LineWidth’,2);