我将表示两个端点p1
,p2
因为我打算使用x
和y
其他东西.我还假设的第一坐标p1
和p2
是X,第二个是ÿ.所以这是一个相当简单的方法:
获得线y = ax + b的等式.在MATLAB中,这可以通过以下方式完成:
x = p1(1):p2(1)
dx = p2(1) - p1(1);
dy = p2(2) - p1(2);
y = round((x - p1(1)) * dy / dx + p1(2));
Run Code Online (Sandbox Code Playgroud)转换的值的x
和y
,以在矩阵元素的指数,并且这些元件设置为1.
idx = sub2ind(size(m), y, x);
m(idx) = 1;
Run Code Online (Sandbox Code Playgroud)这是一个小的10×10矩阵的例子:
%// This is our initial conditon
m = zeros(10);
p1 = [1, 4];
p2 = [5, 7];
%// Ensure the new x-dimension has the largest displacement
[max_delta, ix] = max(abs(p2 - p1));
iy = length(p1) - ix + 1;
%// Draw a line from p1 to p2 on matrix m
x = p1(ix):p2(ix);
y = round((x - p1(ix)) * (p2(iy) - p1(iy)) / (p2(ix) - p1(ix)) + p1(iy));
m(sub2ind(size(m), y, x)) = 1;
m = shiftdim(m, ix > iy); %// Transpose result if necessary
Run Code Online (Sandbox Code Playgroud)
结果是:
m =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
更新:我已经修补了这个算法,当dy > dx时,通过将具有最大位移的维度视为x维度,然后在必要时转置结果.