From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Angle between two vectors
Date: Wed, 12 Oct 2011 18:54:26 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 42
Message-ID: <j74np2$m9p$>
References: <ef5ce9c.-1@webcrossing.raydaftYaTP> <fjj9nj$fia$> <fjk0tg$jli$> <fjlrpl$gii$> <fjm4u4$i8o$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1318445666 22841 (12 Oct 2011 18:54:26 GMT)
NNTP-Posting-Date: Wed, 12 Oct 2011 18:54:26 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 3113727
Xref: comp.soft-sys.matlab:745828

"Roger Stafford" wrote in message <fjm4u4$i8o$>...
> "salih tuna" <> wrote in message <fjlrpl$gii
> $>...
> > Hi,
> > thanks a lot for your reply. yes they are in 2d, sorry i
> > forgot to mention.
> > i tried to apply the formula but i am getting wrong result.
> > for example i want to calculate the angle between a = [1 1]
> > and b = [0 -1] which is 225 degrees. with this formulae i
> > got 243.4. i couldn't see where i am doing the mistake.
> > thanks a lot in advance
> > salih
> > 
> > "Roger Stafford" <>
> > wrote in message <fjk0tg$jli$>...
> > >  angle = mod(atan2(y2-y1,x2-x1),2*pi); % Range: 0 to 2*pi
> --------
>   I certainly owe you an apology, Salih.  That formula I gave you is very, very 
> wrong.  I can't imagine what I was thinking about when I wrote it.  Chalk it up 
> to momentary insanity!  :-)  The correct computation should be as follows.
>   Assuming a = [x1,y1] and b = [x2,y2] are two vectors with their bases at the 
> origin, the non-negative angle between them measured counterclockwise 
> from a to b is given by
>  angle = mod(atan2(x1*y2-x2*y1,x1*x2+y1*y2),2*pi);
>   As you can see, this bears a close relationship to the three-dimensional 
> formula I wrote last July 10.  The quantities, x1*y2-x2*y1 and x1*x2+y1*y2 
> are, respectively, the sine and cosine of the counterclockwise angle from 
> vector a to vector b, multiplied by the product of their norms - that is, their 
> cross product and the dot product restricted to two dimensions.  The 'atan2' 
> function then gives the angle between them ranging from -pi to +pi, and the 
> 'mod' operation changes this so as to range from 0 to 2*pi, as you requested.
> Roger Stafford

Hate to belabor this thread, but I'm not getting the above equation to work.  It works for the one test case you mention in a later thread a=(1,1) and b=(0,-1), but not much else.  For example a=(0,1) and b=(1,0) gives 180.  I can get the angle easily by using atan2(x2,y2) - atan2(x1,y1) but I haven't thought of a clever way to deal with wrapping without using a couple of if-then statements.  (I want the answer to fall between -180 and 180)