Direction of a vector

10,826

Solution 1

vec = [x y]
dist = sqrt(sum(vec.^2)) % i.e. sqrt(x^2 + y^2)
dir = atan(y/x) % i.e. atan(vec(2) / vec(1))

Solution 2

The correct way to compute the direction is to use atan2() instead of atan(), because atan() cannot resolve the quadrants and gives wrong angles in the second and third quadrant (i.e. when x is negative). As an example,

x = -1;
y = -1;
dir = atan(y/x);  % returns 0.78540 rad = 45 deg

Which is clearly the wrong direction. However, atan2() yields

dir2 = atan2(y, x); % returns -2.3562 rad = -135 deg.

If you insist on using atan(), you must check the sign of the x-argument and add pi whenever it is negative.

Share:
10,826
brucezepplin
Author by

brucezepplin

Updated on November 22, 2022

Comments

  • brucezepplin
    brucezepplin over 1 year

    If I have :

    a=magic(9);
    

    How do I compute the direction and magnitude of vectors between any two points in a? For example if I define vec = [a(1,1) a(2,2)], would the direction of the vector be defined as: vecdir = a(1,1) - a(2,2)?

    • Dan
      Dan over 11 years
      but a(1,1) and a(2,2) are scalars, so how can there be a direction between them? Do you mean the vector created by letting the X component be a(1,1) and the Y component be a(2,2)?
    • brucezepplin
      brucezepplin over 11 years
      how do i create such a vector that you have mentioned?
    • Franck Dernoncourt
      Franck Dernoncourt over 11 years
      as you said, vec = [a(1,1) a(2,2)]
    • brucezepplin
      brucezepplin over 11 years
      in that case, how do i find the direction of vec as I have defined it?