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.

Upvotes: 0

Views: 223

Answers (1)

M.Bergen
M.Bergen

Reputation: 174

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)))

Upvotes: 1

Related Questions