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 に答える