Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to generate such a matrix from two vectors in R?

Tags:

r

matrix

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?

like image 545
Paw in Data Avatar asked Sep 29 '20 07:09

Paw in Data


1 Answers

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
like image 191
Ronak Shah Avatar answered Oct 22 '22 03:10

Ronak Shah