% GSA code v1.1.
% Generated by Esmat Rashedi, 2010.
% "	E. Rashedi, H. Nezamabadi-pour and S. Saryazdi,
%揋SA: A Gravitational Search Algorithm? Information sciences, vol. 179,
%no. 13, pp. 2232-2248, 2009."
%
%This function calculates the accelaration of each agent in gravitational field. eq.7-10,21.
function a=Gfield(M,X,G,Rnorm,Rpower,ElitistCheck,iteration,max_it)


[N,dim]=size(X);
final_per=1; %In the last iteration, only 1 percent of agents apply force to the others.

%%%%total force calculation
if ElitistCheck==1
    kbest=final_per+(1-iteration/max_it)*(100-final_per);
    kbest=round(N*kbest/100);%kbest in eq. 21. total force that acts on agent i in a dimension d   %round 四舍五入
else
    kbest=N; %eq.9.
end
% The time complexity is O(k^2)
[~, ds]=sort(M,'descend'); % Ms表示降序的质量,ds表示之前的位置
if size(ds)== 1
    ds=ones(N,1);
end

E = zeros(N,dim);
a = zeros(N,dim);
temp_G = 0;

for i=1:N
    for ii=1:kbest
        j=ds(ii);
        if j~=i
            R=norm(X(i,:)-X(j,:),Rnorm); %Euclidian distanse.
            E(i,:) = E(i,:) + rand(1,dim).*(M(j)).*((X(j,:)-X(i,:))./(R^Rpower+eps));%eps存在的意义是防止两物体靠在一起分母为0
            % Calculate the gravitation constant of new gravitational field
            for k = 1:ii
                temp_G = temp_G + G(ds(k));
            end
            temp_G = temp_G / ii;
            zeros
            a(i,:) = a(i,:) + temp_G .* E(i,:);
            temp_G = 0;
        end
    end
end



%acceleration
% a=E.*G; %note that Mp(i)/Mi(i)=1





