Find Angle Between Vectors and Lines in MATLAB
1. Angle Between Two Vectors (2D or 3D)
Use dot(), norm(), and acosd() to get the angle in degrees directly.
% Define vectors
u = [1, 2, 3];
v = [4, -1, 2];
% Compute cosine value
cosTheta = dot(u, v) / (norm(u) * norm(v));
% Clamp value to [-1, 1] to prevent roundoff errors
cosTheta = max(min(cosTheta, 1.0), -1.0);
% Compute angle in degrees and radians
thetaDeg = acosd(cosTheta);
thetaRad = acos(cosTheta);
fprintf('Angle: %.2f degrees (%.4f radians)\n', thetaDeg, thetaRad);
Output: Angle: 62.19 degrees (1.0854 radians)
2. Angle Between Two 2D Lines (From Slopes)
If you have lines defined by slopes m1 and m2, compute the angle with atan2d() or atand():
% Line 1: y = 3x + 1 (m1 = 3)
% Line 2: y = -2x + 4 (m2 = -2)
m1 = 3;
m2 = -2;
% Acute angle between the two lines
thetaDeg = atand(abs((m2 - m1) / (1 + m1 * m2)));
fprintf('Acute angle between lines: %.2f degrees\n', thetaDeg);
Output: Acute angle between lines: 45.00 degrees
3. Angle Between Two Lines Given by Endpoints (3D or 2D)
Convert endpoints into direction vectors by subtracting start and end points:
% Line 1 endpoints: P1 to P2
P1 = [0, 0, 0];
P2 = [2, 3, 5];
% Line 2 endpoints: Q1 to Q2
Q1 = [1, 1, 1];
Q2 = [4, 0, 2];
% Direction vectors
d1 = P2 - P1;
d2 = Q2 - Q1;
% Acute angle between lines (uses absolute value on dot product)
cosTheta = abs(dot(d1, d2)) / (norm(d1) * norm(d2));
cosTheta = min(cosTheta, 1.0);
angleDeg = acosd(cosTheta);
fprintf('Angle between 3D lines: %.2f degrees\n', angleDeg);
Output: Angle between 3D lines: 63.66 degrees
4. Angle Between Batches of Vectors (Matrix Operations)
To calculate angles between multiple pairs of vectors simultaneously without writing loops:
% Matrices containing N vectors (each row is a vector)
U = [1, 0, 0; 0, 1, 0; 1, 1, 0];
V = [0, 1, 0; 0, 1, 0; 1, 0, 0];
% Row-wise dot product and row-wise norms
dotProds = sum(U .* V, 2);
normU = sqrt(sum(U.^2, 2));
normV = sqrt(sum(V.^2, 2));
cosAngles = dotProds ./ (normU .* normV);
cosAngles = max(min(cosAngles, 1.0), -1.0);
anglesDeg = acosd(cosAngles);
disp('Angles in degrees:');
disp(anglesDeg);
Output:
90.00
0.00
45.00
Summary of Built-in MATLAB Functions
dot(u, v): Calculates vector dot product.norm(u): Calculates vector magnitude.acosd(x): Returns inverse cosine in degrees.acos(x): Returns inverse cosine in radians.atan2d(y, x): Returns four-quadrant inverse tangent in degrees.
```
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Explore similar technical troubleshooting questions and verified MATLAB solutions: