R中的速度计算

时间:2018-09-06 15:01:17

标签: r simulation

给定我在不同帧上具有对象的x和y位置,如何从数据集中计算对象的速度。这是我正在使用的代码。

for (i in 1:(nrow(accdata))) {
  if (row1$Object == row2$Object) {
    d <- integer()
    v <- integer()
    d <- c(sqrt((row1$midx - row2$midx) ^ 2 + (row1$midy - row2$midy) ^ 2))
    v <- d / framerate 
  }
}

我得到一个距离和速度的单一值。我应该得到一个向量,因为数据集有很多行

1 个答案:

答案 0 :(得分:0)

(row1$midx - row2$midx) * framerate(row1$midy - row2$midy) * framerate给出速度矢量的x和y分量(请检查帧频的维数,通常将其作为帧频以fps〜1 / s为单位)。请参阅下面的代码以获取圆周运动的速度分量和速度本身:

# data simulation
# circular motion
frame_rate <- 60 # in fps
dt <- 1 / frame_rate # in secs
t <- seq(1, (10 * pi), dt)
x <- sin(t) # in meter
y <- cos(t) # in meters
accdata <- data.frame(midx = x, midy = y) # coordinates, in meters

# velocity calculations
dx <- c(NA, diff(accdata$midx))
dy <- c(NA, diff(accdata$midy))
vx <- dx / dt
vy <- dy / dt
v <- sqrt(vx ^ 2 + vy ^ 2)
res <- cbind(accdata, dx, dy, vx, vy, v)
head(res)

输出:

       midx      midy          dx          dy        vx         vy         v
1 0.8414710 0.5403023          NA          NA        NA         NA        NA
2 0.8503587 0.5262034 0.008887753 -0.01409891 0.5332652 -0.8459344 0.9999884
3 0.8590103 0.5119583 0.008651548 -0.01424507 0.5190929 -0.8547043 0.9999884
4 0.8674232 0.4975710 0.008412940 -0.01438728 0.5047764 -0.8632367 0.9999884
5 0.8755952 0.4830456 0.008171994 -0.01452549 0.4903197 -0.8715294 0.9999884
6 0.8835240 0.4683859 0.007928779 -0.01465967 0.4757267 -0.8795800 0.9999884