I think this will do what you want, though there may be ways of speeding it
up further.
theta.dist <- function(x)
as.dist(acos(crossprod(t(x))/sqrt(crossprod(t(rowSums(x*x)))))/pi*180)
***********************************
Simon Gatehouse
CSIRO Exploration and Mining,
Newbigin Close off Julius Ave
North Ryde, NSW
Mail: PO Box 136, North Ryde
NSW 1670, Australia
Phone: 61 (2) 9490 8677
Fax: 61 (2) 9490 8921
Mobile: 61 0407 130 635
E-mail: [EMAIL PROTECTED]
Web Page: http://www.csiro.au/ <http://www.csiro.au/>
-----Original Message-----
From: Xiao-Jun Ma [mailto:[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> ]
Sent: Friday, November 28, 2003 10:02 AM
To: '[EMAIL PROTECTED] '
Subject: [R] Getting rid of loops?
I wrote a function to calculate cosine distances between rows of a matrix.
It uses two loops and is slow. Any suggestions to speed this up? Thanks in
advance.
theta.dist <- function(x){
res <- matrix(NA, nrow(x), nrow(x))
for (i in 1:nrow(x)){
for(j in 1:nrow(x)){
if (i > j)
res[i, j] <- res[j, i]
else {
v1 <- x[i,]
v2 <- x[j,]
good <- !is.na(v1) & !is.na(v2)
v1 <- v1[good]
v2 <- v2[good]
theta <- acos(v1%*%v2 / sqrt(v1%*%v1 * v2%*%v2 )) / pi * 180
res[i,j] <- theta
}
}
}
as.dist(res)
}
______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
<https://www.stat.math.ethz.ch/mailman/listinfo/r-help>
[[alternative HTML version deleted]]
______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help