Hello,
I've created a function for making a binary map of a line, similar to the makeCircle function which makes a binary map of a circle or an arc. I made this mainly because I wanted to model planar transducers, but it can probably be useful in other ways as well. Here's the function:
function line = makeLine(x,z,r0,v,lineLength,lineThick)
% MAKELINE - Create a binary map of a line on a 2D grid.
%
% DESCRIPTION:
% makeLine creates a binary map of a line within a two-dimensional
% grid (the line position is denoted by 1's in the matrix with 0's
% elsewhere).
%
% USAGE:
% line = makeLine(xx,zz,x0,z0,xu,zu,length,thick)
%
% INPUTS:
% x, z - vectors of x and z positions of the grid
% r0 - vector r0 = [x0 z0] indicating line center point
% v - vector v = [vx vz] perpendicular to the line
% length - length of line
% thick - thickness of line
%
% OUTPUTS:
% line - 2D binary map of a line
%
% ABOUT:
% author - Martin H. Skjelvareid
% date - 12th Oct 2010
% last update -
%
% See also makeCircle
% COMMENT:
% The function works by calculating the vector between the reference
% point r0 and all other points. This vector is then projected along
% the unity vectors parallel to and perpendicular to the line. If the
% distance parallel to / perpendicular to the line is within the
% constraints on the line length and thickness, the corresponding
% grid point is added to the binary map of the line.
%% Get size of input
Nx = length(x); % Number of x points
Nz = length(z); % Number of z points
%% Create direction vectors of unity length
v = v/norm(v); % Unity vector along line
vt = [-v(2) v(1)]; % Unity vector perpendicular to line
%% Create matrix representations of vectors
[Z,X] = ndgrid(z,x); % Expand z and x to matrices
R = cat(3,X,Z); % Concatenate X and Z along 3. dim
R0 = repmat(reshape(r0,1,1,2),Nz,Nx); % Reshape r0 to 3. dim, duplicate
V = repmat(reshape(v,1,1,2),Nz,Nx); % Reshape v to 3. dim, duplicate
Vt = repmat(reshape(vt,1,1,2),Nz,Nx); % % Reshape vt to 3. dim, duplicate
%% Calculate projections along/perdendicular to line
dR = R - R0; % Calc. diff. vector between all points and r0
distAlong = abs(sum(dR.*Vt,3)); % Project diff. vec. along line
distPerpend = abs(sum(dR.*V,3)); % Project diff. vec. prepend. to line
%% Create binary mask of points within length/thickness constraints
line = double((distAlong <= lineLength/2) & (distPerpend <= lineThick/2));
and here's a simple test script:
close all
clearvars
dx = 0.1;
x = -5:dx:5;
z = -5:dx:5;
r0 = [-1 -2]; % Line center point
v = [2 3]; % Vector perpendicular to line
width = 3; % Line width
thick = dx; % Line thickness
line = makeLine(x,z,r0,v,width,thick);
figure
imagesc(x,z,line)
axis image
colormap(1-gray(256))
hold on
quiver(r0(1),r0(2),v(1),v(2),0)
legend('Vector perpend. to line')
If you find this little code snippet useful, feel free to include it in future versions. :-)