function A = ntrue(N,varargin)
%  NTRUE - Logical array with a specific number of true values
%    NTRUE(N,P,Q, ...) or NTRUE(N,[P Q ...]) creates a logical array of size
%    [P Q ...] with N randomly positioned true values. NTRUE(N,P) is short for 
%    NTRUE(N,P,P). All arguments (N,P,Q,...) are positive scalars.
%
%    NTRUE(N) creates a N-ny-N matrix with N true values.
%
%    Example:
%    NTRUE(5,3,4) % creates a 3-by-4 matrix with 5 true (and 7 false)
%    values, for instance:
%    %   0     0     0     0
%    %   1     1     0     0
%    %   1     0     1     1
%
%   See also TRUE, FALSE, ONES, ZEROS, 
%   and SLM, SHAKE, NONES (on the MatLab FEX)

% for Matlab R13
% version 1.1 (sep 2006)
% (c) Jos van der Geest
% email: jos@jasen.nl

% 1.0 (apr 2006) creation
% 1.1 (sep 2006) algorithm after all checks
%                replaced call to randperm by a direct call to sort

if nargin>1,
    try
        A = false(varargin{:}) ;
    catch
        % show the error, but adapt so that it does not show the call to .
        a = lasterror ;
        error(strrep(a.message(23:end),'false',mfilename)) ;
    end
end
    
if ~isnumeric(N) || numel(N)~= 1 || ndims(N)>2 ||  fix(N)~=N || N < 0,
    error('ntrue:positiveinteger','First argument should be a positive integer') ;
end

if nargin==1,
    A = false(N) ;
end

if N==0,
    return
elseif N >= numel(A),
    warning('ntrue:maximumN','Number of true values is (larger than) the number of elements') ;
    A(:) = true ;
else
    [ii,ii] = sort(rand(1,numel(A))) ;
    A(ii(1:N)) = true ;
end
