0

I want to calculate the angle of two n-dimensional vectors having a reference point also. What I have found so far is this for 3D:

p1 =  [DN(3,1) DN(3,2) DN(3,3)];
p2 =  [DN(2,1) DN(2,2) DN(2,3)];
refpoint = [DN(1,1) DN(1,2) DN(1,3)];
v1 = p1 - refpoint;
v2 = p2 - refpoint;
angNew = rad2deg(atan2(norm(cross(v1,v2)),dot(v1,v2)));
disp(angNew)

Thnx very much in advance.

Grzegorz
  • 231
  • 1
  • 10
  • The remains are always found on Stackoverflow. As if .. – Divakar Jan 06 '16 at 19:48
  • Assuming your question is "how do I generalize this to n dimensions?", the answer is that `atan2(norm(cross(v1,v2)),dot(v1,v2));` generalizes to n-dimensions. – TroyHaskin Jan 06 '16 at 19:54
  • @TroyHaskin When I run this with 4 dimensions I got the error : A and B must be of length 3 in the dimension in which the cross product is taken. – Grzegorz Jan 06 '16 at 19:58
  • Though the duplicate is marked in Python, the accepted solution by Alex Martelli is readable and you should be able to reproduce the results. Look at the last method at the end of his code.... which is essentially what Troy Haskin has outlined below. – rayryeng Jan 06 '16 at 19:59
  • 1
    @PhilipC. Ah. I guess the cross doesn't generalize to higher dimensions ... forgot about that. Then the version `acos(dot(v1,v2)/(norm(v1)*norm(v2))` should suffice. ... which the dup actually uses, go figure. – TroyHaskin Jan 06 '16 at 20:01
  • @TroyHaskin this I have found with transposing the first vector on dot(). Though it prints a table. Sorry for being naive(I am from Computer Science district) but I would like the one angle. Thnx very much for the reply. – Grzegorz Jan 06 '16 at 20:05
  • As long as `v1` and `v2` are vectors, `dot` should return a scalar. Why are you transposing the vectors? – TroyHaskin Jan 06 '16 at 20:10
  • I had found this http://math.stackexchange.com/questions/1288580/how-to-calculate-the-angle-between-two-vectors-in-high-dimensional-space – Grzegorz Jan 06 '16 at 20:12
  • 1
    @PhilipC Transposing one vector then multiplying it with another computes the dot product. That's why you see the transpose. You can either use `dot(v1,v2)` **without** transposing either of the vectors or you can do `v1.'*v2` assuming `v1` and `v2` are both column vectors. It computes the same thing. – rayryeng Jan 06 '16 at 20:14
  • 1
    Gotcha. Do: `acos((u(:).'*v(:))/(norm(u)*norm(v)))` When you create a vectors like `[DN(3,1) DN(3,2) DN(3,3)];` (with spaces), it creates a row vector, so transposing and multiplying performs an outer product instead of an inner product. The syntax `u(:)` turns it into a column vector. – TroyHaskin Jan 06 '16 at 20:15

0 Answers0