calculate angle between vectors in matlab

You can use the dot product formula to calculate the angle between two vectors in Matlab. The dot product is defined as the product of the magnitudes of the two vectors and the cosine of the angle between them.

Here is an example code that calculates the angle between two vectors in degree:

main.m
% Define two vectors
vec1 = [1 2 3];
vec2 = [4 5 6];

% Calculate magnitude of vectors
mag1 = norm(vec1);
mag2 = norm(vec2);

% Calculate dot product of vectors
dot_prod = dot(vec1, vec2);

% Calculate cosine of angle
cos_theta = dot_prod / (mag1 * mag2);

% Calculate angle in degree
angle_deg = acosd(cos_theta);

disp(['The angle between the two vectors is ' num2str(angle_deg) ' degrees.'])
395 chars
19 lines

Output:

main.m
The angle between the two vectors is 11.972 degrees.
53 chars
2 lines

gistlibby LogSnag