% This code is written by Rajib Kumar Bhattacharjya, Department of Civil
% Engineering, Indian Institute of Technology Guwahati for demonstrating
% the working principle of simple differential evolution. This code is 
% written only for academic purpose and The developer is
% not responsible for any loose or damage incurred due to the use of this
% code.
% Please write your objective function in the 'fitness' function below and
% also define the parameters 
function simpleDe()

clear all;
popSize = 30; % Population size
noVar = 2; % Number of variables
fileName = 'fitness'; % Name of the fitness function
gen = 500; % Maximum generation
F=0.2; % factor
cp = 1;
LB = [0 0]; % Lower bound of the variables
UB = [5 5]; % Upper bound of the variables

% initialize population
for i=1:noVar
    pop.X(:,i) = LB(i)+(UB(i)-LB(i))*rand(popSize,1);
end

% Calculation of fitness value
for i=1:popSize
    pop.f(i)=feval(fileName,pop.X(i,:));
end

% Main loop
for i=1:gen
    for k =1:popSize
        r1 = genIrand(popSize);
        r2 = genIrand(popSize);
        r3 = genIrand(popSize);
        v=pop.X(r1,:)+F*(pop.X(r2,:)-pop.X(r3));
        Irand = genIrand(noVar);
        for j=1:noVar
            if(rand(1,1)<cp && j==Irand)
                u(j) = v(j);
            else
                u(j) = pop.X(k,j);
            end
        end
        newfit=feval(fileName,u);
        if (newfit<pop.f(k))
            pop.X(k,:)=u;
            pop.f(k)=newfit;
        end
    end
    [fval,I] = min(pop.f);
    XX = pop.X(I,:);
    disp('Generation  X value     Objective value');
    disp(num2str([i XX fval]));
end

end

function f = fitness( x1 )
    x=x1(1);
    y=x1(2);
    f = (x^2+y-11)^2+(x+y^2-7)^2; % Objective function 1
    
    
%     f = (x+2*y-7)^2+(2*x+y-5)^2; % Objective function 2
    
%     f = (1.5-x+x*y)^2+(2.25-x+x*y^2)^2+(2.625-x+x*y^3)^2; % Objective
%     function 3
end

function r = genIrand(B)

r = ceil(B*rand(1,1));

end