我已经实现了一些代码,以使用指定的尺寸生成3D笛卡尔坐标曲面。然而,这是相当慢的,并且是实现该方法的非常低效的方法。有人可以帮助我提供一种需要更少迭代的更好方法吗?
library(rgl)
density <- 1
#test data 5 x 10 x 15 box
a <- seq(from = 1, to = 5, by = density)
b <- seq(from = 1, to = 10, by = density)
c <- seq(from = 1, to = 15, by = density)
#length of each dimension
aL <- length(a)
bL <- length(b)
cL <- length(c)
#data.frame to store 3D box
test = data.frame()
#calculate the indices for the nested for loop
inner <- bL * cL
outer <- aL * bL * cL
tracker <- 1:inner
tracker <- c(tracker, (outer - (inner) + 1):outer)
for(x in 1:(aL-2)) {
for(i in 1:bL) {
if(i == 1 || i == bL) {
tracker <- c(tracker, (inner+1):(inner+cL))
} else {
tracker <- c(tracker, inner + 1)
tracker <- c(tracker, inner + cL)
}
inner <- inner + cL
}
}
#loops over all possible combinations and uses only the indices above
iter <- 1
for(x in a) {
for(y in b) {
for(z in c) {
if(any(iter == tracker)) {
test <- rbind(test, data.frame(x = x, y = y, z = z))
}
iter <- iter + 1
}
}
}
points3d(test)
答案 0 :(得分:0)
虽然有机会通过预先分配矢量和数据帧来加快速度,但您是否考虑过分别生成曲面的六个面,然后将它们粘在一起?
expand.grid
函数使此操作变得简单:
faces_xy <- expand.grid(x = a, y = b, z = c(min(c), max(c)))
faces_xz <- expand.grid(x = a, y = c(min(b), max(b)), z = c)
faces_yz <- expand.grid(x = c(min(a), max(a)), y = b, z = c)
surface <- unique(rbind(faces_xy, faces_xz, faces_yz))
每个faces_
变量都包含指定平面上的两个面。调用unique
是为了消除人脸共享的边缘上的重复点。
我没有进行任何基准测试,也没有费心去分析每种方法的复杂性,但是我希望这样做会更快。