Search code examples
matlabtime-seriesangle

Get angle between two lines of a time series in Matlab


How can I calculate angle in degrees between lines AB and BC in Matlab?

Time-series


Solution

  • It's a little bit of an unusual request, but the code below should do the trick :).

    % X and Y coordinates of your time series
    X = (1:9)';
    Y = [-3;-1;-1.2;-4.5;-5.5;.2;-2;-.5;-.4];
    
    angle_rad = zeros(size(X,1)-2,1);         % Preallocate the angle vector
    for i = 1:(size(Y,1)-2)                 % Loop over all vector pairs
    
        % Vectors:
        a = [X(i+1)-X(i);Y(i+1)-Y(i)];      % first vector
        b = [X(i+2)-X(i+1);Y(i+2)-Y(i+1)];  % second vector
    
        % Vector properties:
        dot_prod = a'*b;
        l_a = norm(a);                      % length of first vector
        l_b = norm(b);                      % length of second vector
    
        % Angle:
        angle_rad(i) = pi - acos(dot_prod/(l_a*l_b));  % [rad]
    end
    angle_deg = angle_rad.*180./pi; % [degrees]
    

    See if this works, but this code is a little clumsy, maybe if we knew what you were using this for, there could be a better option?