Hi,

 

I apologize for this repeat posting, which I first posted yesterday. I would
appreciate any hints on solving this problem:

 

I have two matrices A (m x 2) and B (n x 2), where m and n are large
integers (on the order of 10^4).  I am looking for an efficient way to
create another matrix, W (m x n), which can be defined as follows:

 

for (i in 1:m){

for (j in 1:n) {

W[i,j] <- g(A[i,], B[j,])

} }

where g(x,y) is a function that takes two vectors and returns a scalar.

 

The following works okay, but is not fast enough for my purpose.  I am sure
that I can do better:

 

for (i in 1:m) {

W[i,] <- apply(B, 1, y=A[i,], function(x,y) g(y,x)) 

}

 

How can I do this in a faster manner? I attempted "outer", "kronecker",
"expand.grid", etc, but with no success.    

 

Here is an example:

 

m <- 2000

n <- 5000

A <- matrix(rnorm(2*m),ncol=2)

B <- matrix(rnorm(2*n),ncol=2)

W <- matrix(NA, m, n)

 

for (i in 1:m) {

W[i,] <- apply(B, 1, y=A[i,], function(x,y) g(y,x)) 

}

 

g <- function(x,y){

theta <- atan((y[2]-x[2]) / (y[1] - x[1]))

theta + 2*pi*(theta < 0)

}

 

Thanks for any suggestions.

 

Best,

Ravi.

 

 

 

----------------------------------------------------------------------------
-------

Ravi Varadhan, Ph.D.

Assistant Professor, The Center on Aging and Health

Division of Geriatric Medicine and Gerontology 

Johns Hopkins University

Ph: (410) 502-2619

Fax: (410) 614-9625

Email: rvaradhan@jhmi.edu

Webpage:  http://www.jhsph.edu/agingandhealth/People/Faculty/Varadhan.html

 

----------------------------------------------------------------------------
--------

 


	[[alternative HTML version deleted]]

