i want to change this python program to matlab

조회 수: 1 (최근 30일)
yared Zeleke
yared Zeleke 2018년 4월 3일
댓글: yared Zeleke 2018년 4월 10일
import random
import string
target = "Hello, World!"
def calc_fitness(source, target):
fitval = 0
for i in range(0, len(source)):
fitval += (ord(target[i]) - ord(source[i])) ** 2
return(fitval)
def mutate(parent1, parent2):
child_dna = parent1['dna'][:]
# Mix both DNAs
start = random.randint(0, len(parent2['dna']) - 1)
stop = random.randint(0, len(parent2['dna']) - 1)
if start > stop:
stop, start = start, stop
child_dna[start:stop] = parent2['dna'][start:stop]
# Mutate one position
charpos = random.randint(0, len(child_dna) - 1)
child_dna[charpos] = chr(ord(child_dna[charpos]) + random.randint(-1,1))
child_fitness = calc_fitness(child_dna, target)
return({'dna': child_dna, 'fitness': child_fitness})
def random_parent(genepool):
wRndNr = random.random() * random.random() * (GENSIZE - 1)
wRndNr = int(wRndNr)
return(genepool[wRndNr])
def dump_genepool(generation, genepool):
for candidate in genepool:
print "%6i %6i %15s" % (
generation,
candidate['fitness'],
''.join(candidate['dna'])
)
print
GENSIZE = 20
genepool = []
for i in range(0, GENSIZE):
dna = [random.choice(string.printable[:-5]) for j in range(0, len(target))]
fitness = calc_fitness(dna, target)
candidate = {'dna': dna, 'fitness': fitness }
genepool.append(candidate)
generation = 0
while True:
generation += 1
genepool.sort(key=lambda candidate: candidate['fitness'])
dump_genepool(generation, genepool)
if genepool[0]['fitness'] == 0:
# Target reached
break
parent1 = random_parent(genepool)
parent2 = random_parent(genepool)
child = mutate(parent1, parent2)
if child['fitness'] < genepool[-1]['fitness']:
genepool[-1] = child

답변 (1개)

yared Zeleke
yared Zeleke 2018년 4월 4일
편집: yared Zeleke 2018년 4월 4일
clc
clear all
target="hello,world!";
function fitval = fitness(source, target)%def calc_fitness;
fitval = 0;
for i = 1 : length(source)
fitval = fitval + (double(target(i)) - double(source(i))) ^ 2;
end
end
function [child_dna,child_fitness]=mutate(parent1,parent2)%def 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);
%child_fitness=calc_fitness(child_dna,target);
child_fitness=0;
end
function [x] = random_parent(genepool , GENSIZE)
wRndNr = rand() * rand() * ( GENSIZE - 1 )
wRndNr = int32(wRndNr); x = genepool(wRndNr);
  댓글 수: 1
yared Zeleke
yared Zeleke 2018년 4월 10일
this is some part of it any one would you finish it up please?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Genomics and Next Generation Sequencing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by