Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angle between two vectors in R

What the most efficient way in the programming language R to calculate the angle between two vectors?

like image 207
Christian Avatar asked Dec 13 '09 20:12

Christian


People also ask

How do you find the angle between two vectors given two vectors?

To find the angle between two vectors a and b, we can use the dot product formula: a · b = |a| |b| cos θ. If we solve this for θ, we get θ = cos-1 [ (a · b) / (|a| |b|) ].

How do you find an angle in R?

In any circle of radius r, the ratio of the arc length ℓ to the circumference equals the ratio of the angle θ subtended by the arc at the centre and the angle in one revolution. Thus, measuring the angles in radians, ℓ2πr=θ2π⟹ ℓ=rθ.

How do you find the angle between two vectors U and V?

So we can compute the angle θ between u and v using the dot product: θ = arccos ( u · v u v ) . u · v = u vcos(0) = u v > 0. , so u · v = u vcos(π/2) = 0.


1 Answers

According to page 5 of this PDF, sum(a*b) is the R command to find the dot product of vectors a and b, and sqrt(sum(a * a)) is the R command to find the norm of vector a, and acos(x) is the R command for the arc-cosine. It follows that the R code to calculate the angle between the two vectors is

theta <- acos( sum(a*b) / ( sqrt(sum(a * a)) * sqrt(sum(b * b)) ) ) 
like image 145
las3rjock Avatar answered Oct 13 '22 22:10

las3rjock