Searching for math expert! angle of vectors in a loop using law of cosines
1 view (last 30 days)
Show older comments
Hello,
I created a loop to get each angle in between two vektors as you can see in the picture. My aim is to get the angle on each sixth point as shwon in the diagramm.
Using the follwing scipt, my resulting angle is always 90°! I can not see the mistake! Probably you do!?
alphaans=int16.empty(1,length(x1),0);
for i = 1:(length(x1)-2)
ax(i)=x1(1,i+1)-x1(1,i);
ay(i)=y1(1,i+1)-y1(1,i);
bx(i)=x1(1,i+2)-x1(1,i+1); %second (b) vector
by(i)=y1(1,i+2)-y1(1,i+1);
cx(i)=x1(1,i)+ax(i)+bx(i); %resulting, leading to third vector
cy(i)=y1(1,i)+ay(i)+by(i);
lcx(i)=x1(1,i+2)-x1(1,i); %third (c) vector
lcy(i)=x1(1,i+2)-x1(1,i);
Ba(i)=sqrt((ax(1,i)^2+ay(1,i)^2)); % norm (a)
Bb(i)=sqrt((bx(1,i)^2+by(1,i)^2)); % norm (b)
Bc(i)=sqrt((lcx(1,i)^2+lcy(1,i)^2)); % norm (c)
alpha(i)=acosd(((Bb(1,i))^2+(Ba(1,i))^2-(Bc(1,i))^2)/(2.*Ba(1,i).*Bb(1,i))); %law of cosines
alphaans(1,i,1)=alpha(i); %put each angle in the array alphaans
end
Thanks!
5 Comments
Mostafa
on 9 Nov 2016
I think you only need to replace each instance of i+6 with i+1 and i+12 with i+2
Cheers.
Accepted Answer
Thorsten
on 9 Nov 2016
Edited: Thorsten
on 9 Nov 2016
% define sample values
x = [1234.77 936.40 681.39 516.59 355.26 82.90];
y = [241.90 155.16 118.73 193.32 408.43 458.74];
% plot values
y = 500 - y; % subtract to make y axis pointing upwards, just for display
% purposes
plot(x, y, 'ko-')
axis equal
grid on
box off
% get angle between successive line elements
vec = [diff(x)' diff(y)'];
for i = 1:size(vec, 1) - 1
u = vec(i,:);
v = vec(i+1,:);
theta(i) = acos( (u * v')/(norm(u)*norm(v)) );
% u * v' is the dot product between u and v
end
rad2deg(theta)
0 Comments
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!