Angle between two vectors in a for loop

10 Ansichten (letzte 30 Tage)
Mateusz Soczalski
Mateusz Soczalski am 6 Jan. 2022
Beantwortet: William Rose am 8 Feb. 2022
I need to find angles between vectors starting from 5th. These are the two loops i wrote:
A = [X;Y];
A = [A; zeros(1,50)];
W_wek = [1 0 0];
%W_wek = [0 1 0];
for k=1:length(A)
W_wek = [A(1,:)-B(1,:); A(2,:)-B(2,:); A(3,:)-B(3,:)];
end
In the first one I'm supposed to get the coordinates of the vectors, the variable looks like this:
In the second for loop i used the atan2d function combined with norm,cross:
Ang=[];
for l=5:length(W_wek)
Ang(l) = atan2d(norm(cross(W_wek(l-1,:),W_wek(l,:))),dot(W_wek(l-1,:),W_wek(l,:)));
end
I was sure it should work but it keeps giving me this error: Index in position 1 exceeds array bounds. Index must not exceed 3.
Any ideas how to fix this?
  1 Kommentar
dpb
dpb am 6 Jan. 2022
for l=5:length(W_wek)
Ang(l) = atan2d(norm(cross(W_wek(l-1,:),W_wek(l,:))),dot(W_wek(l-1,:),W_wek(l,:)));
length() is a dangerous function -- it's defined as max(size(x)) so for your case above it will return 50.
You then use it as the upper limit on the l looping index and use l as the row index for the subscripting expression into the array. You've got the indices/limits turned around.
I recommend to not use length here at all and in most cases you'll want a specific size value just like here...

Melden Sie sich an, um zu kommentieren.

Antworten (1)

William Rose
William Rose am 8 Feb. 2022
(I deleted my comment because I posted it before it was complete, and because I intended to post an answer rather than a comment. I'm not very good at the mechanics of posting.)
W_wek=2*rand(3,50)-1; %points uniform in the (-1...+1) cube
N=length(W_wek);
angle=zeros(1,N-5); %allocate array for angles
for i=5:N
angle(i)=acosd(dot(W_wek(:,i),W_wek(:,i-1))/(norm(W_wek(:,i))*norm(W_wek(:,i-1))));
end
fprintf('Angle: min=%.2f, max=%.2f, mean=%.2f\n',min(angle),max(angle),mean(angle));
Angle: min=0.00, max=170.65, mean=78.95
Angle is between 0 and 180.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by