And now for a MATLAB (R2018a) version:
%% Calculate the Anlge Between 3 Points in 3D Space
clear, clc, close all
format compact
%% Test calculating the angle between 3 points
%
% Find angle (∠BC) between vector AB and vector BC
%
% * <--- C (100, 100, 120)
% /
% /
% /
% * <------- A (100, 100, 80)
% |
% |
% |
% * <------- B (100, 175, 80)
aa = [100, 100, 80];
bb = [100, 175, 80];
cc = [100, 100, 120];
theta = angle_3points(aa, bb, cc);
fprintf("Angle: %.4f degrees\n", theta); % Result: Angle: 28.0725 degrees
%% Function definition for calculating the angle between 3 points in 3D space
function theta = angle_3points(a, b, c)
% THETA = ANGLE_3POINTS(A, B, C)
% Function to calculate angle between 3 points
%
% Inputs:
% a: The first point. 1x3 vector.
% b: The second point. 1x3 vector.
% c: The third point. 1x3 vector.
% Outputs:
% theta: The angle between vector ab and vector bc in degrees.
if nargin < 3 || isempty(a) || isempty(b) || isempty(c)
error 'Parameters `a`, `b`, and `c` are all required inputs.';
end
% Check the sizes of vectors a, b, and c
[n, m] = size(a);
if n ~= 1 || m ~= 3
error 'Parameter `a` must be a 1x3 vector.';
end
[n, m] = size(b);
if n ~= 1 || m ~= 3
error 'Parameter `b` must be a 1x3 vector.';
end
[n, m] = size(c);
if n ~= 1 || m ~= 3
error 'Parameter `c` must be a 1x3 vector.';
end
clear n m;
v1 = a - b;
v1_mag = sqrt(sum(v1.^2));
v1_norm = v1 ./ v1_mag;
v2 = c - b;
v2_mag = sqrt(sum(v2.^2));
v2_norm = v2 ./ v2_mag;
theta = v1_norm(1)*v2_norm(1) + v1_norm(2)*v2_norm(2) + ...
v1_norm(3)*v2_norm(3);
theta = acos(theta) * 180 / pi();
end