Hi:

Another alternative is

crossprod(A)

which is meant to produce an optimized A'A  (not the vector cross-product
from intro physics :)

Example:

A <- matrix(rpois(9, 10), ncol = 3)
> A
     [,1] [,2] [,3]
[1,]    6   10   14
[2,]    7    5   16
[3,]   12   16   10
> t(A) %*% A
     [,1] [,2] [,3]
[1,]  229  287  316
[2,]  287  381  380
[3,]  316  380  552
> crossprod(A)
     [,1] [,2] [,3]
[1,]  229  287  316
[2,]  287  381  380
[3,]  316  380  552

A little test:

f <- function(A) {
     U <- crossprod(A)
     diag(U) <- 0
     U
  }
g <- function(A) {
     U <- t(A) %*% A
     diag(U) <- 0
     U
  }

# matrix multiplication on a 100 x 10 matrix
> system.time(replicate(1000, g(matrix(rpois(1000, 10), ncol = 10))))
   user  system elapsed
   0.24    0.00    0.23

# crossprod
> system.time(replicate(1000, f(matrix(rpois(1000, 10), ncol = 10))))
   user  system elapsed
   0.20    0.00    0.21

# matrix multiplication on a 10 x 100 matrix
> system.time(replicate(1000, g(matrix(rpois(1000, 10), ncol = 100))))
   user  system elapsed
   1.72    0.17    1.89

# crossprod
> system.time(replicate(1000, f(matrix(rpois(1000, 10), ncol = 100))))
   user  system elapsed
   0.47    0.09    0.56


HTH,
Dennis

On Thu, Nov 11, 2010 at 5:19 PM, Michael Bedward
<michael.bedw...@gmail.com>wrote:

> On 12 November 2010 02:21, David Winsemius <dwinsem...@comcast.net> wrote:
> >
> >> The fastest and easiest solution is
> >>
> >>  t(A) %*% A
> >
> > That is really elegant. (Wish I could remember my linear algebra lessons
> as
> > well from forty years ago.) I checked it against the specified output and
> > found that with one exception that the OP had planned for the diagonal to
> be
> > filled with zeroes. So that could be completed by a simple modification:
> >
> > temp <- t(A) %*% A
> > diag(temp) <- 0
> > temp
> >
>
> Excellent solution ! Small is beautiful :)
>
> Michael
>
> ______________________________________________
> R-help@r-project.org mailing list
> 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.
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
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.

Reply via email to