u <- rnorm(1000)
v <- c(1,2,3)
A <- matrix(0,nrow=3,ncol=1000)
for (i in 1:3)
{
for (j in 1:1000)
{
A[i,j] <- (u[j]-v[i])^2
}
}
I believe there must be a better way to generate matrix A from vectors u and v. Can anybody help me out here?
We can use outer
:
u <- rnorm(10)
v <- c(1,2,3)
B <- t(outer(u, v, `-`)^2)
identical(A, B)
#[1] TRUE
Benchmark :
library(microbenchmark)
u <- rnorm(100000)
v <- rnorm(100)
p1 = function(){
A <- matrix(0,nrow=length(v),ncol=length(u))
for (i in 1:length(v))
{
for (j in 1:length(u))
{
A[i,j] <- (u[j]-v[i])^2
}
}
}
p2 = function(){
B <- t(outer(u, v, `-`)^2)
}
microbenchmark(p1(),p2(),times = 10)
#Unit: milliseconds
# expr min lq mean median uq max neval
# p1() 3359.8119 3367.9753 3383.0087 3374.1323 3397.3018 3420.7159 10
# p2() 326.7757 352.0144 459.9654 386.4121 584.3815 694.2599 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With