Cosine matrix

36 views
Skip to first unread message

mishery

unread,
Sep 19, 2008, 4:54:12 AM9/19/08
to CorpLing with R
Hi.

Is there a way to get a matrix of cosines between vectors?

I have a 518 column vectors of length 2160 and I was hoping to get a
518*518 matrix of the cosines between these vectors.

Basically I would like to the equivalent of cor(mydata) but for
cosines not correlations between the vectors. But of course,
cos(mydata) gives me the cosines of the individual values.

Can anyone help?

Thanks

- Mike

Stefan Th. Gries

unread,
Sep 19, 2008, 12:11:09 PM9/19/08
to corplin...@googlegroups.com
This should do the trick:

# some random data
x<-matrix(rnorm(1000), ncol=10)

require(amap)
1-Dist(t(x), method="pearson")

HTH,
STG
--
Stefan Th. Gries
-----------------------------------------------
University of California, Santa Barbara
http://www.linguistics.ucsb.edu/faculty/stgries
-----------------------------------------------

Ken Williams

unread,
Sep 19, 2008, 12:33:58 PM9/19/08
to CorpLing with R
Or you can just use matrix algebra:

> x<-matrix(rnorm(40), ncol=5)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1502795 -1.03924422 0.04422048 0.34105320 1.1524531
[2,] -1.7948242 -0.29985823 -0.70274315 -0.35564664 -2.2606329
[3,] -0.3682100 1.60098884 0.52262554 -0.05829224 -0.7012830
[4,] 0.5163998 -2.01919506 -1.12951358 1.55975383 1.0453210
[5,] -1.9530669 0.91230939 -0.22734366 1.13818820 0.3863500
[6,] 0.4367691 -0.09917415 0.89987130 1.11857546 0.1385893
[7,] 0.8961183 -0.25895326 -1.42279126 -0.34125845 0.9977009
[8,] -1.6253010 -0.43304923 -0.35767055 -0.68865311 1.1977955

> y <- sweep(x, 2, sqrt( colSums( x*x ) ), `/`) # Normalize
> t(y) %*% y
[,1] [,2] [,3] [,4] [,5]
[1,] 1.00000000 -0.2618860 0.08483994 0.07413309 0.3023032
[2,] -0.26188599 1.0000000 0.52274794 -0.30239278 -0.4309406
[3,] 0.08483994 0.5227479 1.00000000 -0.00876695 -0.2344688
[4,] 0.07413309 -0.3023928 -0.00876695 1.00000000 0.2923369
[5,] 0.30230321 -0.4309406 -0.23446878 0.29233689 1.0000000

-Ken

mishery

unread,
Sep 23, 2008, 3:30:57 AM9/23/08
to CorpLing with R
Thanks.

The matrix algebra version worked great, thank you. And I had not come
across "sweep" before, this will be very useful, so again thank you.

Can I just ask what the last backslash bit of function does?
Reply all
Reply to author
Forward
0 new messages