R: Efficiently construct a matrix from a vector and fill it with certain conditions

I would like to construct a matrix A

in accordance with a vector k

such that there A_ij

is a minimum k_i

and everywhere k_j

.

Currently I can do it like this:

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 is relatively slow, how can I improve the computational efficiency?

Thank.

+3


source to share


1 answer


This seems to speed up the process 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 

      

+4


source







All Articles