Untitled

                Never    
% Weights and values declaration
w10 = [2, 4, 6, 7, 3, 1, 2, 4, 3, 2, 6, 4, 2, 3, 1, 2, 3, 3, 5, 1];
v10 = [3, 6, 5, 9, 11, 2, 4, 7, 5, 6, 1, 3, 2, 6, 4, 5, 2, 3, 3, 4];

w15 = [2, 4, 3, 5, 1, 2, 3, 6, 5, 4, 2, 7, 5, 3, 1];
v15 = [2, 6, 5, 7, 9, 2, 3, 1, 5, 4, 4, 2, 8, 1, 10];

w20 = [2, 4, 6, 7, 3, 1, 2, 4, 3, 2, 6, 4, 2, 3, 1, 2, 3, 3, 5, 1];
v20 = [3, 6, 5, 9, 11, 2, 4, 7, 5, 6, 1, 3, 2, 6, 4, 5, 2, 3, 3, 4];

weights = w10 %[2,3,1,2];
values = v10 %[5,7,2,4];

%capacity of knapsack, population and num of generations definition
maxCapacity=20;
population= 55;
amountOfGenerations= 50;

%initial parents and offsprings declaration
BinaryParents=[];
BestParent=[];
BinaryOffsprings=[];

% PARENTS(WEIGTHS , VALUES)
Parents=zeros(population,2);

%random generation of 1st parents
BinaryParents=rand(population,size(weights,2));
BinaryParents=round(BinaryParents);



for generation = 1 : amountOfGenerations
    Parents=zeros(population,2);
    %calculations parents weights and values
    for i = 1 : size(BinaryParents,1)
        for j = 1 : size(BinaryParents,2)
            Parents(i,1)=Parents(i,1) + BinaryParents(i,j)*weights(j);
            Parents(i,2)=Parents(i,2) + BinaryParents(i,j)*values(j);
        end
        if Parents(i,1) > maxCapacity
            Parents(i,2)=0;
        end
    end
    
    
    temp_parents_4_crossover=[];
    [BestParent, BestParent_index] = max(Parents(:,2));
   
    BinaryOffsprings = [];
    
    %creating a matrix of temp parents (without the best one) for crossover
    for index = 1 :  size(BinaryParents,1)
        if index ~= BestParent_index
            temp_parents_4_crossover=[temp_parents_4_crossover; BinaryParents(index,:)];
            
        end
    end
    %crossover
    for offspring_index=1: 2 : size(temp_parents_4_crossover,1)
        for i = 1 : size(temp_parents_4_crossover, 2)
            if i <= size(temp_parents_4_crossover,2)/2
                BinaryOffsprings(offspring_index ,i) = temp_parents_4_crossover(offspring_index,i);
                BinaryOffsprings(offspring_index+1 ,i) = temp_parents_4_crossover(offspring_index+1,i);
            else
                BinaryOffsprings(offspring_index ,i) = temp_parents_4_crossover(offspring_index+1,i);
                BinaryOffsprings(offspring_index+1 ,i) = temp_parents_4_crossover(offspring_index,i);
            end
        end
        
        %Offsprings_binary(offspring_index,:)= [Offsprings_binary(offspring_index),temp_parents_4_crossover(offspring_index,(1:half))];
    end
    BinaryOffsprings=[BinaryOffsprings;BinaryParents(BestParent_index,:)];
    
    
   
    BinaryParents=BinaryOffsprings;
    
end

[BestParent, BestParent_index] = max(Parents(:,2));
BestParent
BinaryParents(BestParent_index,:)
Parents

Raw Text