function [fmerit] = merit_func(w,X_curr,Fit_curr,X_DB)
%MERIT_FUNC Summary of this function goes here
% This function calculates the merit order of the different positions 
    [rankedFit,~]=sort(Fit_curr,'ascend'); %sort the approximated/surrogate fitness value
    smin=rankedFit(1); %best app fobj:  smin as the minimum surrogate value among the sample points
    smax=rankedFit(end);%worst app fobj:  smax as the maximum surrogate value among the sample points
    S=zeros(size(Fit_curr)); % Init Scaled surrogate vector
    distance=zeros(size(X_curr,1),size(X_DB,1)); % Init distance surrogate vector (Euclidean norm of a difference vector)
    for i=1:size(X_curr,1)
        S(i)=(Fit_curr(i)-smin)/(smax-smin); %Scaled surrogate 
        for j=1:size(X_DB,1)
            distance(i,j)=norm(X_curr(i,:)-X_DB(j,:)); %Define xj, j = 1,…,k as the k evaluated points. 
            %Define dij as the distance from sample point i to evaluated point j.
        end
    end
    dmin=min(min(distance)); % dmin = min(dij) 
    dmax=max(max(distance)); % dmax = max(dij)
    dx=zeros(size(Fit_curr)); % Init d(x): is the minimum distance of the point x to an evaluated point
    Dx=zeros(size(Fit_curr)); 
    fmerit=zeros(size(Fit_curr));
    for i=1:size(X_curr,1)
        dx(i)=min(distance(i,:));
        Dx(i)=(dmax-dx(i))/(dmax-dmin); % Scaled distance.
        fmerit(i)=w*S(i)+(1-w)*Dx(i);
        % A large value of w gives importance to the surrogate values, causing the search to minimize the surrogate. 
        %A small value of w gives importance to points that are far from evaluated points, leading the search to new regions
        %During the Search for Minimum phase, the weight w cycles through these four values, as suggested by Regis and Shoemaker [2]: 0.3, 0.5, 0.8, and 0.95.
    end
end
%_______________________________________________________________________________________________________________________________%
% by Pedro Bento November 2023
% When using please cite and refer this code and its author!
