stuttungr - 7 months ago 71

R Question

I have a matrix describing a 2D surface and I need to be able to calculate values along the surface for an arbitrary line.

This is best explained by an example

`#x and y axes`

x=c(1:100)

y=c(1:100)

# 2D Matrix function defined as 0 except for a middle box filled with 1

M=matrix(0,nrow=100,ncol=100)

M[40:60,40:60]=1

# define two points

x1=50

y1=50

x2=23

y2=80

# plot contour graph of M, add points (x1,y1) and (x2,y2)

# and a line connecting the two

contour(x,y,M)

points(x1,y1,col=2)

points(x2,y2,col=3)

lines(c(x1,x2),c(y1,y2),lty=2)

What I want to do is to get values of M along the line from (x1,y1) to (x2,y2), for instance at the values (xvec,yvec) where xvec=seq(x1,x2,length.out=N) and likewise for yvec.

Is there a simple way to do this in R?

Sincerely

Answer

It actually pretty easy using the capacity of the "[" function to accept a two column matrix (and here assuming `N <- 20`

):

```
M[ cbind(xvec,yvec) ]
[1] 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
```

Because indices are truncated, the values won't necessary be those of the nearest points when the arguments are not integers.

Source (Stackoverflow)