function [pointMatrix probabilityVector] = sampleNormal(...
    nDim, nSample, mean, cov)
% sample from n-dim standard normal distribution
%
% Syntax: [pointMatrix, probabilityVector] = sampleNormal(nDim, nSample)
%   OR     .. = sampleNormal(.., mean, cov)
%
% THIS IS NO USER FUNCTION

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2013 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>.

% The standard normal distribution has the parameters:
%   mean = zeros
%   cov = eye
% A coordinate transformation of these x:
%     y = a + B*x
% results in a normal distribution of y with parameters:
%     mean = a
%     cov = B*B'
% Hence, given the parameters, the transformation parameters are:
%     a = mean
%     B = chol(cov)

% points
pointMatrix = randn(nDim, nSample);

% some conveniance
if ~exist('mean', 'var') || isempty(mean)
    mean = zeros(nDim, 1);
end
if ~exist('cov', 'var') || isempty(cov)
    cov = eye(nDim);
end

% get the transformation matrix
try
    B = chol(cov);
catch me
    error('elk:distribution:wrongInput', ['The covariance matrix must ' ...
        'be symmetric and positive definite ''chol'' has thrown the ' ...
        'following message: ' me.message]);
end

pointMatrix = bsxfun(@plus, B*pointMatrix, mean);
probabilityVector = mvnpdf(pointMatrix', mean', cov)';
