% FUNCTION DA = DELTA_ANGLE( A1, A2 )
% 
% To compute signed angle difference ( A1 - A2 ) in radians.
% Output is a value between -pi and pi.
% 

function da = delta_angle( a1, a2 )
  
  if nargin < 2
    error( 'delta_angle needs two arguments' );
  end
  
  siz1 = size( a1 );
  siz2 = size( a2 );  
  n1 = sum( siz1 > 1 );
  n2 = sum( siz2 > 1 );
  
  if (n1>0) & (n2>0) & ~all( siz1 == siz2 )
    
    % If both arguments are non-scalar but of different dimensions
    error( ['delta_angle: a1 and a2 must have same size (or one of them' ...
	    ' must be scalar)'] );
  end
  
  da = mod( a1 - a2, 2 * pi );  % Between 0 and 2*pi
  
  aux = find( da > pi );
  da( aux ) = da( aux ) - 2*pi;  % Between -pi and +pi
  