简体   繁体   English

如何找到序列矩阵中两点之间的距离?

[英]How do I find the distance between two points in a matrix of sequences?

I have a large matrix that is composed of 0s and 1s.我有一个由 0 和 1 组成的大矩阵。 I would like to find the distance between 1s.我想找到1s之间的距离。

For example, if I have the first row of a matrix as例如,如果我有一个矩阵的第一行

 0  0  1  0  1  1  0

I want the output我想要 output

3  2  1  

3 is the location of the first 1 2 is the distance between the first and second 1 1 is the location of the second and the third 1 3 是第一个 1 的位置 2 是第一个和第二个 1 之间的距离 1 是第二个和第三个 1 的位置

How do I accomplish this?我该如何做到这一点?

One option is which with diff .一种选择是which with diff Convert the vector to logical, find the index where the values are 1 with which and get the diff erence of index positionsvector转换为逻辑,找到值为 1 的索引which并获得索引位置的diff

i1 <- which(as.logical(v1))
out <- c(i1[1], diff(i1))
out
#[1] 3 2 1

data数据

v1 <- c(0, 0, 1, 0, 1, 1, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM