Try crossprod(A) instead.
> A <- matrix(rnorm(1e6), 100, 1000)
> dos.time(apply(A, 2, function(a) t(a) %*% a))
[1] 5.187
> dos.time(for(i in 1:ncol(A)) { t(A[,i])%*%A[,i] })
[1] 4.958
> dos.time(p1 <- t(A) %*% A)
[1] 1.071
> dos.time(p2 <- crossprod(A))
[1] 0.721
> all.equal(p1, p2)
[1] T
Regards,
Sundar
Adam Brentnall wrote:
Dear users of S-news
As part of a function I would like to calculate transpose(A) %*% A so
that the first row of transpose(A) is matched with the 1st row of A. The
second row of Transpose(A) is matched with the second column of A, etc.
For example if:
A = 1 2 3
4 5 6
Then the operation would return
transpose(A) %*% A = 14
77
I have used three methods on an example where A is an 18x900 matrix:
1. Apply: e.g. apply(A,2,function(A)t(A)%*%A))
Dos time of function = 4.736s
2. For loop: e.g. for( i in 1: x){test[i]<-t(A[,i])%*%A[,i]}
Dos time of function = 4.837s
3. Matrix multiplication: e.g. diag(t(test)%*%test)
Dos time of function = 1.181s
If I don't do this part of the procedure and use a made-up matrix for A
then the Dos time of the function is 0.531s.
I would like the function to run as quickly as possible to use in
resampling. I have the feeling that there must be a better way to do
this than method 3. If anyone has encountered this problem before I
would be happy to hear if there is a better way.
Splus: S-PLUS® 6.1 for Windows, Professional, Release 1
Operating system: Windows 2000, SP4
Best wishes
Adam Brentnall
a.r.brentnall@maths.soton.ac.uk
Research Student
Dept Mathematics
University of Southampton UK
--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news
|