0

This question is not about drawing lines in plots. I want to a function that will take effect on 2D matrices (or others) in the following way.

We have an initial matrix:

0 0 0  
0 0 0  
0 0 0  

A line from (1,1) to (3,3) would produce the following:

1 0 0  
0 1 0  
0 0 1 

A line from (1,2) to (3,1) would produce the following:

0 1 0  
0 1 0  
1 0 0

I know that I can code a function that does this, but I would like to avoid this. Thx in advance.

4

3 回答 3

2

我认为您正在努力实现这一目标-

# coordinates
xmin = 1
xmax = 3
ymin = 2
ymax = 1
# resolution
howmanystepsx <- 3
howmanystepsy <- 3

# deciding which coordinates 'fall' on the path
dt <- data.frame(
  x = round(seq(from = xmin, to = xmax, length.out = howmanystepsx),0),
  y = round(seq(from = ymin, to = ymax, length.out = howmanystepsy),0)
)

# creating a grid
plotgrid <- matrix(nrow = max(xmax,xmin), ncol = max(ymax,ymin))

# marking points that 'fall' on the path
for ( i in seq(nrow(dt)))
{
  plotgrid[dt[i,'x'],dt[i,'y']] <- 1
}

plotgrid[is.na(plotgrid)] <- 0

输出:

> plotgrid
     [,1] [,2]
[1,]    0    1
[2,]    0    1
[3,]    1    0
于 2013-11-13T15:18:01.883 回答
1

如果您创建dt为矩阵,则无需循环即可:

# coordinates
xmin = 1
xmax = 3
ymin = 2
ymax = 1
# resolution
howmanystepsx <- 3
howmanystepsy <- 3
dt=cbind(
   round(seq(from = xmin, to = xmax, length.out = howmanystepsx),0),
   round(seq(from = ymin, to = ymax, length.out = howmanystepsy),0))
plotgrid <- matrix(0,nrow = max(xmax,xmin), ncol = max(ymax,ymin))

然后是魔法:

plotgrid[dt]=0
plotgrid

我想知道 Bresenham 算法是否是您正在寻找的...

于 2013-11-13T18:14:03.303 回答
1

想发布我最终使用的内容:

getLineCoor <- function (x1, y1, x2, y2) 
{
    steps <- max( abs(x1-x2), abs(y1-y2) ) + 1 
    return ( cbind(round(seq(x1, x2, length.out=steps) ,0),
                   round(seq(y1, y2, length.out=steps) ,0)) )
}

我需要在步骤中“+1”,因为在某些情况下,这条线缺少坐标(像素)。感谢这两个答案:)。

于 2013-11-15T13:05:23.380 回答