function y = diag(X,k)
%y=diag(X,k)
%Extract the diagonal elements of a matrix
%Convert a vector to a diagonal matrix

%       S.Halevy 7/31/92
%       Copyright (c) 1992 by the MathWizards

if nargin < 1
   y=[];
   return;
elseif nargin < 2
    k=0;
elseif nargin>2
    error('diag - too many input arguments')
end

k0=k+1;		% k=0 for the main diagonal

if isvector(X)   % VECTOR
   X=X(:);
   nx = length(X);
   ny = nx + abs(k);
   y=zeros(ny);

   k0 = expr_sel(k>=0,ny*k,abs(k))+1;

   for ik=1:nx
       y(k0)=X(ik);
       k0 += ny+1;
   end
else    % MATRIX
   [m,n] = size(X);
   mstep = m+1;
   k0=1;
   if k>0
      k0+=m*k;  % first element
      n -= k;       % row shift
   else             % negative k
      k0 += (-k); % first element
      m -=   (-k); % col shift
   end
   k0 = max(1, k0);       % first element
   ny = max(0, min(m,n)); % size of output
   y=zeros(ny,1); % empty if ny<=0
   if ny>0
     iy=1:ny;
     y(iy)=X(k0+mstep*(iy-1))';
  end
end
