Angle between multiple unit vectors contained within a matrix.

12 views (last 30 days)
Hi all,
This should be pretty simple but it's escaping me.
I have two matrices (a and b) which contain 10 unit vectors. I would like to calculate the angle between the ten pairs. When I try the method below it gives me a single value as the norm function normalises the whole matrix.
Any thoughts would be most welcome.
% Example vectors. They won't be the same when used.
a_single = [0,0,1];
b_single = [1,0,1];
a_norm = a_single./norm(a_single);
b_norm = b_single./norm(b_single);
% Repeat for 10 elements
a = repmat(a_norm, [10,1]);
b = repmat(b_norm, [10,1]);
% Calculate angle between them.
cosOfAngle = max(min(dot(a,b)/(norm(a)*norm(b)),1),-1);
angle = real(acosd(cosOfAngle))

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 14 Feb 2023
norm as you have used, outputs the norm of the whole array.
If you want to calculate the individual angles between pairs, use vecnorm to calculate norm of each row corresponding to each (unit) vector and modify the dot product (dimension)
%random data
a_single = rand(10,3)
a_single = 10×3
0.3528 0.0048 0.2489 0.5492 0.6751 0.4745 0.3893 0.3847 0.7515 0.5101 0.6794 0.9666 0.6592 0.2736 0.1370 0.5459 0.6470 0.4218 0.3201 0.7294 0.2315 0.6281 0.9073 0.6228 0.5957 0.2334 0.5095 0.7180 0.9331 0.2483
%normalising each vector i.e. each row
a = a_single./vecnorm(a_single,2,2)
a = 10×3
0.8171 0.0112 0.5764 0.5541 0.6811 0.4787 0.4188 0.4138 0.8083 0.3964 0.5280 0.7511 0.9070 0.3765 0.1886 0.5772 0.6841 0.4459 0.3859 0.8793 0.2791 0.4957 0.7161 0.4915 0.7284 0.2853 0.6230 0.5967 0.7755 0.2064
%verifying the norm
sqrt(sum(a(1,:).^2))
ans = 1
%similarly for b
b_single = rand(10,3);
b = b_single./vecnorm(b_single,2,2);
ang = acosd(dot(a,b,2))
ang = 10×1
40.4755 34.4773 37.3944 8.2491 47.6204 26.8094 21.0703 41.7596 40.1300 30.9465

More Answers (1)

Rob Malkin
Rob Malkin on 14 Feb 2023
Should someone read this in the future...
% Vector method
B = a_s.*b;
dotprod = sqrt(B(:,1).^2 + B(:,2).^2 + B(:,3).^2) ;
magnitude_a_s = norm(a_s);
magnitude_b = sqrt(b(:,1).^2 + b(:,2).^2 + b(:,3).^2) ;
cosTheta = dotprod./(magnitude_a_s.*magnitude_b);
ThetaInDegrees = real(acosd(cosTheta));

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!