Info

This question is closed. Reopen it to edit or answer.

I want to get child_fitness=0 i got some eror please any one figure it out let me know thanks?

1 view (last 30 days)
clear;close all;clc;
GENSIZE=20;
target = input('Enter a string (max 30 chars in length): ', 's');
genepool=[];
pop= char(randi(127,GENSIZE,length(target)))
for i=1:GENSIZE
dna = pop(i,:);
fitness = calc_fitness(dna, target)
genepool(i,:)=(fitness)
end
while fitness ~=0
parent1 = get_parent(genepool);
parent2 = get_parent(genepool);
child = mutate(parent1, parent2);
if fitness < genepool(end).fitness
genepool(end) = child
end
end
function [fitval]= calc_fitness(source, target)%def calc_fitness;
fitval=0;
for i = 1 : length(source)
fitval= fitval + (double(target(i)) - double(source(i))) ^ 2;
end
endfunction [child_dna,fitness]=mutate(parent1,parent2)
child_dna =parent1(1,:);
start=randi(size(parent2(1,:)),1,1);
stop=randi(size(parent2(1,:)),1,1);
if(start>stop)
tmp=start;
start=stop;
stop=start;
end
child_dna(start:stop)=parent2(1,start:stop);
charpos=randi(size(child_dna),1,1);
child_dna(charpos)=char(uint8(child_dna(charpos))+randi(3,1,1)-2);
fitness = calc_fitness(child_dna, target)
end
function [x] = get_parent(genepool , GENSIZE)
wRndNr = rand() * rand() * ( GENSIZE );
wRndNr = floor(wRndNr);
if wRndNr ==0
wRndNr =1;
end
x = genepool(wRndNr,:);
end

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!