フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

how to fix this code ??

1 回表示 (過去 30 日間)
Firas Al-Kharabsheh
Firas Al-Kharabsheh 2016 年 4 月 20 日
閉鎖済み: Walter Roberson 2016 年 4 月 20 日
MaxIt=100; % Maximum Number of Iterations
nPop=25; % Population Size
pc=0.8; % Crossover Percentage
nc=2*round(pc*nPop/2); % Number of Offsprings (also Parnets)
pm=0.3; % Mutation Percentage
nm=round(pm*nPop); % Number of Mutants
mu=0.02; % Mutation Rate
CostFunction=@(x) Fitness_function(x); % Cost Function
nVar=50; % Number of Decision Variables
VarSize=[1 nVar];
empty_individual.Position=[];
empty_individual.Cost=[];
pop=repmat(empty_individual,nPop,1);
for i=1:nPop
% Initialize Position
pop(i).Position=randi([0 1],m);
% Evaluation
pop(i).Cost=CostFunction(pop(i).Position);
end
% Sort Population
Costs=[pop.Cost];
[Costs, SortOrder]=sort(Costs);
pop=pop(SortOrder);
% Store Best Solution
BestSol=pop(1);
% Array to Hold Best Cost Values
BestCost=zeros(MaxIt,1);
% Store Cost
WorstCost=pop(end).Cost;
for it=1:MaxIt
% Calculate Selection Probabilities
if UseRouletteWheelSelection
P=exp(-beta*Costs/WorstCost);
P=P/sum(P);
end
% Crossover
popc=repmat(empty_individual,nc/2,2);
for k=1:nc/2
% Select Parents Indices
if UseRouletteWheelSelection
i1=RouletteWheelSelection(P);
i2=RouletteWheelSelection(P);
end
if UseTournamentSelection
i1=TournamentSelection(pop,TournamentSize);
i2=TournamentSelection(pop,TournamentSize);
end
if UseRandomSelection
i1=randi([1 nPop]);
i2=randi([1 nPop]);
end
% Select Parents
p1=pop(i1);
p2=pop(i2);
% Perform Crossover
[popc(k,1).Position, popc(k,2).Position]=Crossover(p1.Position,p2.Position);
% Evaluate Offsprings
popc(k,1).Cost=CostFunction(popc(k,1).Position);
popc(k,2).Cost=CostFunction(popc(k,2).Position);
end
popc=popc(:);
% Mutation
popm=repmat(empty_individual,nm,1);
for k=1:nm
% Select Parent
i=randi([1 nPop]);
p=pop(i);
% Perform Mutation
popm(k).Position=Mutate(p.Position,mu);
% Evaluate Mutant
popm(k).Cost=CostFunction(popm(k).Position);
end
% Create Merged Population
pop=[pop
popc
popm]; %#ok
% Sort Population
Costs=[pop.Cost];
[Costs, SortOrder]=sort(Costs);
pop=pop(SortOrder);
% Update Worst Cost
WorstCost=max(WorstCost,pop(end).Cost);
% Truncation
pop=pop(1:nPop);
Costs=Costs(1:nPop);
% Store Best Solution Ever Found
BestSol=pop(1);
% Store Best Cost Ever Found
BestCost(it)=BestSol.Cost;
% Show Iteration Information
disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCost(it))]);
end
where the fitness_function is
function z = Fitness_function (x)
A = [ 0 1 0 1 0 0 1 0 0 1 ; 0 0 0 0 0 0 1 1 1 1 ; 1 1 1 0 1 1 1 1 1 1 ; 1 0 0 1 0 0 1 0 0 1 ; 1 1 0 1 0 1 0 0 1 1 ];
z = (sum(sum(A ~= x)));
end

回答 (0 件)

この質問は閉じられています。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by