Reputation: 1106
I have a four segments on the plane defined by coordinats:
A <- matrix(c(0, 4, 4, 0, 0, # x
0, 0, 3, 3, 0), ncol=2) # y
x <- A[,1]
y <- A[,2]
n <- dim(x)
xx <- c()
yy <- c()
The segment's lengths are great 1
. I heed to split all segments with step equals 1
.
My attempt is below. I have computed the length of i-th segment, dist
, and now working with a horizontal segment only. I should add new values of x
-coordinats then repeat dist-1
times y
-coordinat.
for (i in 1:n-1){
dist <- sqrt((x[i] - x[i+1])^2 + (y[i] - y[i+1])^2)
if (!is.null(dist) & length(dist) > 0 & dist[1] > 1)
{
# horizontal segment, 'y' is const
if (y[i] - y[i+1] == 0)
{
# split a horizontal segment on (dist-1) parts with step 1
tmp <- c(seq(from = min(x[i], x[i+1]),
to = max(x[i], x[i+1])))
# remove 1st and last elements
xx <- c(xx, tmp[2 : (length(tmp)-1)])
yy <- c(yy, rep(y[i], dist-1));
} # if
} #if
#} # i
xx;yy;
Output is:
> x
[1] 1 2 3 1 2 3
> y
[1] 0 0 0 3 3 3
C <- matrix(c(x,y), ncol=2)
plot(A, col='red', type= 'l', xlim=c(min(A[,1]),max(A[,1])),
ylim=c(min(A[,2]),max(A[,2])), xlab='x', ylab='y');
points(A, col='black', pch = 22);
points(C, col='red', pch = 21);
grid()
Question. How to split segments by equation of a line from 2 points?
https://algs4.cs.princeton.edu/91primitives/
Upvotes: 0
Views: 172
Reputation: 1714
I'm sorry but my understanding of what you clearly want is not perfect. But maybe it is to find all the equation or trace all segments between 2 points from the above exemple ?
If I use segments
function in R to trace 10 * 10 segments, is it what you want ?
all_points <- unique(rbind(A, C))
indices <- expand.grid(1:10, 1:10)
plot(all_points, xlim = c(0, 4), ylim = c(0, 3), xlab = "X", ylab = "Y")
for(i in 1:10){
segments(x0 = all_points[indices[i, 1], 1],
y0 = all_points[indices[i, 1], 2],
x1 = all_points[indices[i, 2], 1],
y1 = all_points[indices[i, 2], 2]
)
}
Upvotes: 1