function retRes = lognchoosek(n,k)
%function retRes = lognchoosek(n,k)
%
% Calculate logarithm of the binomial coefficient (n, k) = n!/k!(n-k)!.
% 
% Input:
%   n: non-negative integer;
%   k: non-negative integers, may be a matrix;
%
% Output:
%   retRes: log(n, k) = log(n!/k!(n-k)!).
%
% Dabao Zhang    June 4, 2013
%
% Revised by:
%
%   Copyright 2013 Dabao Zhang.

[nR,nC] = size(k);
vk = reshape(k,nR*nC,1);
idx1 = find(vk>n/2);
vk(idx1) = n-vk(idx1);
[uk,idx1,idx2] = unique(vk);    % vk = uk(idx2);

if( any(uk<0) )   % k may be a matrix???
    error('  lognchoosek: should have 0<=k<=n...'); 
end
for j=1:length(uk)
    tmpN = (n-uk(j)+1):n;
    tmpD = 1:uk(j);
    tmpN = log(tmpN./tmpD);
    uk(j) = sum(tmpN);
end

retRes = reshape(uk(idx2),nR,nC);
