简体   繁体   English

如何计算数组和矩阵之间的距离

[英]How to calculate the distance between an array and a matrix

Consider a matrix A and an array b. 考虑矩阵A和数组b。 I would like to calculate the distance between b and each row of A. For instance consider the following data: 我想计算b与A的每一行之间的距离。例如,考虑以下数据:

A <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15), 3, 5, byrow=TRUE)
b <- c(1, 2, 3, 4, 5)

I would expect as output some array of the form: 我希望将某些形式的数组作为输出:

distance_array = c(0, 11.18, 22.36)

where the value 11.18 comes from the euclidean distance between a[2,] and b : 其中值11.18来自a[2,]b之间的欧式距离:

sqrt(sum((a[2,]-b)^2))

This seems pretty basic but so far all R functions I have found allow to compute distance matrices between all the pairs of rows of a matrix, but not this array-matrix calculation. 这似乎很基本,但是到目前为止,我发现的所有R函数都允许计算矩阵的所有行对之间的距离矩阵,但不能进行此数组矩阵计算。

I would recommend putting the rows a A in list instead of a matrix as it might allow for faster processing time. 我建议将行A放在列表中而不是矩阵中,因为这样可以缩短处理时间。 But here's how I would do it with respect to your example 但是,关于您的示例,这是我的处理方式

A <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15), 3, 5, byrow=TRUE)

b <- c(1, 2, 3, 4, 5)

apply(A,1,function(x)sqrt(sum((x-b)^2)))

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

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