[R] Fast Matrix Computation

Shi, Tao shidaxia at yahoo.com
Sat May 22 21:20:50 CEST 2010


One way to do it:

apply(B, 1, function(x) t(apply(A, 1, function(y) abs(y-x) )) )





----- Original Message ----
> From: David Neu <david at davidneu.com>
> To: r-help at r-project.org
> Sent: Sat, May 22, 2010 10:35:32 AM
> Subject: [R] Fast Matrix Computation
> 
> Hi,

I have two (large) matrices A and B of dimensions (m,n) and (p,n) 
> respectively.

I'd like to see if the is a fast way to compute a new 
> matrix C with
dimension (m*p,n) in which each row in C is found by applying 
> some
function f to each pair of rows (x,y) where x is a row in A and y is 
> a
row in B.

For example, if

A <- matrix(c(1, 2, 3, 4, 5, 6), 
> byrow=TRUE, ncol=3)
B <- matrix(c(7, 8, 9), byrow=TRUE, ncol=3)

and 
> f <- function(x,y) abs(y-x)

then

C <- matrix(c(6, 6, 6, 3, 
> 3, 3), byrow=TRUE, ncol=3)

Many 
> thanks!

Cheers,
David

______________________________________________

> ymailto="mailto:R-help at r-project.org" 
> href="mailto:R-help at r-project.org">R-help at r-project.org mailing list

> href="https://stat.ethz.ch/mailman/listinfo/r-help" target=_blank 
> >https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting 
> guide http://www.R-project.org/posting-guide.html
and provide commented, 
> minimal, self-contained, reproducible code.



More information about the R-help mailing list