On Wed, 25 Feb 2004, Sundar Dorai-Raj wrote:
> Try crossprod(A) instead.
That was my idea, but that seems not to be what he actually wants but
rather diag(diag(crossprod(t(A)))) given the numerical example.
I think we need to know if it is A or t(A), if A is 18 x 900. If the
answer is a 900-long vector, diag(crossprod(A)) is too wasteful.
For diag(diag(crossprod(t(A)))) I would try
A <- matrix(1:6, 2, byrow=T)
diag(rowSums(A^2))
>
> > 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
^^^ col?
> > 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
--
Brian D. Ripley, ripley@stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
|