简体   繁体   中英

How to calculate the distance between an array and a matrix

Consider a matrix A and an array b. I would like to calculate the distance between b and each row of A. For instance consider the following data:

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 :

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.

I would recommend putting the rows a A in list instead of a matrix as it might allow for faster processing time. 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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