function [newPoints dMin] = DoEPMCPoint(numberOfNewPoints, existingPoints, candidatePoints)
% DOEPMCPOINT generates homogeneous distributed data samples (Pseudo-Monte Carlo approach).
%
% Procedure description: For all random samples (candidate points) the distances to all  
% existing points are calculated and the minimal distance dMin is determined. Next, the
% point is added to the data set that has maximum dMin.
%
%
%   [newPoints] = DoEPMCPoint(numberOfNewPoints, existingPoints, candidatePoints)
%
%
% INPUT
%
%   numberOfNewPoints:  1 x 1  Number of samples that have to be added.
%   existingPoints:     ? x p  Matrix containing already measured data points.
%   candidatePoints:    ? x p  Matrix containing candidate points for selection.
%
%
% OUTPUT
%
%   newPoints:          ? x p  New points for measurement (query points).
%
%
% HiLoMoTDoE - Nonlinear System Identification Toolbox for Design of Experiments
% Benjamin Hartmann, 05-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


% Define existing points
index = [];
newPoints = [];
numberOfAllSamples = size(existingPoints,1);
N = numberOfAllSamples - 1 + numberOfNewPoints;

% Generate homogeneous distributed data samples.
% Procedure description:
% For all random samples (candidate points) the distances to all existing points are calculated and the minimal distance dMin is determined.
% Next, the point is added to the data set that has maximum dMin.

% Initiatlize the vector containing the minimal distances
dMin = inf(1,size(candidatePoints,1));
for k = 1:N
    % Evaluate the distances of candidate points to the lastly added point u(k,:)
    distanceOfk = sqrt(sum(bsxfun(@minus,candidatePoints,existingPoints(k,:)).^2,2))';
    % Take over the smallest distances in the distance vector dMin
    dMin = min([distanceOfk;dMin],[],1);
    
    if k >= numberOfAllSamples
        % Select the point with the largest dMin-value
        [~, idxMax] = max(dMin);
        % Update existing points with selected candidate point
        existingPoints = [existingPoints; candidatePoints(idxMax,:)];
        % Update index vector
        index = [index; idxMax];
        newPoints = [newPoints; candidatePoints(idxMax,:)];
        
    end
end
end