function [wn,z] = damp(a,delta_t)
% [wn,z] = damp(A,delta_t)
% DAMP	Natural frequency and damping factor for continuous or discrete systems.
%
% damp(A) displays a table of the natural frequencies and 
% damping ratios for the continuous-time dynamics matrix.
%
% damp(A,delta_t) displays a table of the natural frequencies 
% damping ratios for the discrete-time dynamics matrix.
% with a sample time step of delta_t
% 
% [wn,z] = damp(A) or [wn,z] = damp(A,delta_t) returns the vectors
%  wn and z of the natural frequencies and damping ratios, without
%  displaying the table of values.  
%
%  The variable A can be in one of several formats:
%
% (1) If A is square, it is assumed to be the state-space dynamics matrix.
%
% (2) If A is a row vector, it is assumed to be a vector of the
%     polynomial coefficients from a transfer function.
%
% (3) If A is a column vector, it is assumed to contain root locations.
%

[m,n] = size(a);

if (n<1 || m<1), wn=0; z=0; return; end

if (m == n)
  r = eig(a);
elseif (m == 1)
  r = (roots(a));
elseif (n == 1)
  r = a;
else
  error('The variable A must be a vector or a square matrix.');
end

if ( nargin == 2 ), r = log(r)/delta_t; end	% discrete time system

for k = 1:n
  wn(k)  = abs(r(k));
  z(k)   = - (real(r(k)) - 2*eps) / (wn(k) + 2*eps);
end

[wns,idx] = sort(abs(wn));	% sort by increasing natural frequency
wn = wn(idx);
z  = z(idx);
r  = r(idx);
wd = wn .* sqrt( abs ( z.^2 - 1 ) );

if nargout == 0 		% Display results on the screen.
  fprintf(' \n');
  fprintf('     Natural               Damped  \n');
  fprintf('    Frequency             Frequency      Eigenvalue \n');
  fprintf('    (cyc/sec)    Damping  (cyc/sec)   real        imag \n');
  fprintf('    -----------------------------------------------------\n');

  for idx = 1:1:n
    fprintf('    %10.5f  %10.5f    %10.5f   %10.5f  %10.5f  \n', wn(idx)/(2*pi) , z(idx), wd(idx)/(2*pi), real(r(idx)), imag(r(idx)) );
  end

  return % Suppress output
end

% ----------------------------------------------------------------------- DAMP
