function p = logistic(X, beta)
  % p = logistic(X, beta)
  % Evaluate logistic function
  %  X is a M x N matrix, columns are data vectors
  %  beta is a M x 1 vector.
  %  p = exp(beta'*X)./(1+ exp(beta'*X)) a 1 x N vector (of doubles).
    
  cnst = log(1e200);
  tmp = beta(:)' * X;
  p = zeros(1, size(X,2));
  idx1 = (tmp>cnst);
  if (any(idx1))
    p(idx1) = 1;
  end
  idx0 = (tmp < -cnst);
  if (any(idx0))
    p(idx0) = 0;
  end
  idx = ~idx0 & ~idx1;
  if (any(idx))
    p(idx) = exp(beta' * X(:, idx));
    p(idx) = p(idx) ./ (1 + p(idx));
  end
  
  return