[英]R: Efficient construct a matrix from a vector and fill it with certain conditions
I would like to construct a matrix A
according to a vector k
such that everywhere A_ij
is the minimum of k_i
and k_j
. 我想根据向量
k
构造矩阵A
,使得A_ij
到处都是k_i
和k_j
的最小值。
Currently, I can do it as follows: 目前,我可以这样做:
k <- c(3, 1, 6, 5)
mm <- outer(k, k, function(x, y) ifelse(x <= y, x, y))
But, if the vecor is large, the code I wrote run relatively slow, how can I improve the computational efficent? 但是,如果vecor很大,我编写的代码运行速度相对较慢,我怎样才能提高计算效率呢?
Thanks. 谢谢。
This seems to speed things up by an order of magnitude: 这似乎加快了一个数量级:
outer(k,k,pmin)
# or if you are only dealing with integers and speed reeaaaly matters:
outer(k,k,pmin.int)
identical(outer(k,k,pmin), outer(k, k, function(x, y) ifelse(x <= y, x, y)) )
#[1] TRUE
k <- 1:5000
system.time(outer(k, k, function(x, y) ifelse(x <= y, x, y)))
# user system elapsed
# 6.21 0.52 6.73
system.time(outer(k,k,pmin))
# user system elapsed
# 0.51 0.03 0.54
system.time(outer(k,k,pmin.int))
# user system elapsed
# 0.48 0.03 0.51
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.