%% Homework Solution: Change BinStrings.m to Solve Knapsack. % % The Knapsack problem uses the following constants (in order) KnapNames={'Bug','Stove','Water','Clothes','Food','Aid','Light','Book','Rain','Bag','Tent','Filter'}; %% Setup the GA parameters ff='testfunction2'; % objective function file name maxit=250; % max number of iterations (for stopping) maxcost=9999999; %Maximum allowable cost (for stopping) popsize=20; % set population size (it is constant) mutrate=0.2; % set mutation rate (a small probability) lenx=12; % Length of the chromosome (20 here) %% Create the initial population pop=round(rand(popsize,lenx)); % random population of 1s % and 0s (using default, 25x12) popKept=0.5; %Fraction of the population to keep keep=floor(popKept*popsize); %How many individuals are kept M=ceil((popsize-keep)/2); % number of matings; 2 mates create 2 offspring % Initialize cost and other items to set up the main loop cost=feval(ff,pop); % calculates population cost using ff [cost,ind]=sort(cost,'descend'); % max element in first entry pop=pop(ind,:); % sorts population with max cost first probs=cost/sum(cost); %Simple normalization for probabilities. % We'll be tracking the following quantities for our plot: maxc(1)=max(cost); % minc contains min of population meanc(1)=mean(cost); % meanc contains mean of population %% MAIN LOOP iga=0; % Initalize the variable used in the loop below. % This will keep track of how many iterations we've % used and will get us out of the loop at the max while igamaxit || cost(1)>maxcost break end end %iga %% Displays the output day=clock; disp(datestr(datenum(day(1),day(2),day(3),day(4),day(5),day(6)),0)) %disp(['optimized function is ' ff]) format short g disp(['popsize = ' num2str(popsize) ' mutrate = ' num2str(mutrate)]); disp(['#generations=' num2str(iga) ' best cost=' num2str(cost(1))]); fprintf('best solution\n%s\n',mat2str(int8(pop(1,:)))); figure(1) iters=0:length(maxc)-1; plot(1:(iga+1),maxc,1:(iga+1),meanc); xlabel('generation');ylabel('cost'); legend('Max cost', 'Mean Cost') for j=1:12 if pop(1,j)==1 fprintf('Include %s\n',KnapNames{j}); end end