【发布时间】:2019-02-23 20:22:02
【问题描述】:
如果我想计算两个向量的n维距离,可以使用如下函数:
a = c(1:10)
b = seq(20, 23, length.out = length(a))
test_fun =
function(x,y) {
return(
sqrt(
sum(
(x - y) ^ 2
)
)
)
}
n_distance = test_fun(a,b)
现在,我想将其扩展为矩阵设置:我想计算两个矩阵的每对行的 n 维距离。
set.seed(123)
a_mtx = matrix(1:30, ncol = 5)
b_mtx = matrix(sample(1:15,15), ncol = 5)
n_distance_mtx =
matrix(
NA,
nrow = nrow(b_mtx),
ncol = nrow(a_mtx)
)
for(i in 1:nrow(b_mtx)) {
for(j in 1:nrow(a_mtx)) {
n_distance_mtx[i,j] =
test_fun(a_mtx[j,], b_mtx[i,])
}
}
n_distance_mtx 的每一列包含a_mtx 和b_mtx 的每一行之间的距离度量(所以n_distance_mtx[,1] 是a_mtx[1,] 和b_mtx[1:3,] 之间的距离。
如果我计算n_distance_mtx 上的列均值,我可以获得a_mtx 中的每一行与b_mtx 的所有行之间的平均距离。
colMeans(n_distance_mtx)
#[1] 23.79094 24.90281 26.15618 27.53303 29.01668 30.59220
所以23.79094是a_mtx[1,]和b_mtx[1:3,]之间的平均距离,24.90281是a_mtx[2,]和b_mtx[1:3,]之间的平均距离,以此类推.
问题:如何在不使用 for 循环的情况下获得相同的解决方案?
我想将此方法应用于具有更大维度(大约数十万行)的矩阵。看看this和this,好像一定有办法用Vectorizedouter函数来完成这个,但是我一直无法生成这样的函数。
test_fun_vec =
Vectorize(
function(x,y) {
outer(
x,
y,
test_fun
)
}
)
test_fun_vec(a_mtx,b_mtx)
#[1] 4 0 2 7 4 6 3 5 1 5 7 5 10 0 9 11 15 17 8 11 9 12 10 16
#[25] 10 22 20 25 15 24
【问题讨论】:
标签: r