MATLAB Answers

## GA implementation in matlab without using the toolbox

Asked by Yasmine Tamimi

### Yasmine Tamimi (view profile)

on 22 Apr 2011
Latest activity Edited by Walter Roberson

### Walter Roberson (view profile)

on 15 Oct 2016

This is my code for implementing ga in matlab:

```% Program for Genetic algorithm to minimize the constrained function ga_test
clear all;
clc;
```
```%%  function f = ga_test(x)
```
```%%  f = 120*x1 + 120*x2 + 120*x3 + 120*x4 + 120*x5 + 120*x6 + 120*x7 + 120*x8 + 120*x9 + 120*x10 + 40*y1 + 40*y2 + 40*y3 + 40*y4 + 40*y5 + 40*y6 + 40*y7 + 40*y8 + 40*y9 + 40*y10+ 40*y11 + 40*y12 + 40*y13 + 40*y14 + 40*y15 + 40*y16 + 40*y17 + 40*y18 + 40*y19+ 40*y20;
```
```% Setup the Genetic Algorithm
```
```fitnessfunction= @ga_test;
```
```N = 1310;  % number of optimization (decision) variables
```
```popsize = 8 ; % set population size = number of chromosomes
```
```max_iteration = 50;  % max number of iterations
```
```minimum_cost = 120;  % minimum cost
```
```mutation_rate = 0.01; % mutation rate
```
```selection_rate = 0.5; % selection rate: fraction of population
```
```nbits = 1;
```
```Nt = nbits*N; % total number of bits in a chormosome
```
```number_mutations = mutation_rate*N*(popsize-1); % number of mutations
```
```% #population members that survive (Nkeep = Xrate*Npop); Nkeep survive for mating, and (Npop - Nkeep) are discarded to make room for the new offspring
```
```keep = floor(selection_rate*popsize);
```
```iga=0; % generation counter initialized
```
```pop=round(rand(popsize,Nt)); % random population of 1s and 0s
```
```cost=feval(fitnessfunction,pop); % calculates population cost using fitnessfunction
```
```[cost,ind]=sort(cost); % min cost in element 1
```
```pop=pop(ind,:); % sorts population with lowest cost first
```
```minc(1)=min(cost); % minc contains min of population
```
```while iga < max_iteration  %Iterate through generations
```
```iga=iga+1; % increments generation counter
```
```% Pair and mate
```
```M=ceil((M-keep)/2); % number of matings weights chromosomes based upon position in list probability distribution function
```
```prob=flipud([1:keep]'/sum([1:keep]));
```
```odds=[0 cumsum(prob(1:keep))];
```
```pick1=rand(1,popsize); % mate #1
```
```pick2=rand(1,popsize); % mate #2
```
```% parents contain the indicies of the chromosomes that will mate
```
```ic=1;
```
```while ic<=M
```
```for id=2:keep+1
```
```if pick1(ic)<=odds(id) & pick1(ic)>odds(id-1)
```
```ma(ic)=id-1;
```
```end % if
```
```if pick2(ic)<=odds(id) & pick2(ic)>odds(id-1)
```
```pa(ic)=id-1;
```
```end % if
```
```end % id
```
```ic=ic+1;
```
```end % while
```
```%_______________________________________________________
```
```% Performs mating using single point crossover
```
```ix=1:2:keep; % index of mate #1
```
```xp=ceil(rand(1,M)*(Nt-1)); % crossover point
```
```pop(keep+ix,:)=[pop(ma,1:xp) pop(pa,xp+1:Nt)];
```
```% first offspring
```
```pop(keep+ix+1,:)=[pop(pa,1:xp) pop(ma,xp+1:Nt)];
```
```% second offspring
```
```%_______________________________________________________
```
```% Mutate the population
```
```number_mutations=ceil((popsize-1)*Nt*mutation_rate); % total number of mutations
```
```mrow=ceil(rand(1,number_mutations)*(popsize-1))+1; % row to mutate
```
```mcol=ceil(rand(1,number_mutations)*Nt); % column to mutate
```
```for ii=1:number_mutations
```
```pop(mrow(ii),mcol(ii))=abs(pop(mrow(ii),mcol(ii))-1);
```
```end
```
```%_______________________________________________________
```
```% The population is re-evaluated for cost decode
```
```cost(2:popsize)=feval(fitnessfunction,pop(2:popsize,:));
```
```%_______________________________________________________
```
```% Sort the costs and associated parameters
```
```[cost,ind]=sort(cost);
```
```pop=pop(ind,:);
```
```%_______________________________________________________
```
```% Stopping criteria
```
```if iga>maxit | cost(1)<mincost
```
```break
```
```end
```
```[iga cost(1)]
```
```end
```

I still didn't run my code because I do't know how shall I write my objective function and the constraints?? And upon what shall I decide the popsize?

Any help will be highly appreciated.

#### 0 Comments

Log in to comment.

## 3 Answers

### gurleen Sohi (view profile)

Answer by gurleen Sohi

### gurleen Sohi (view profile)

on 14 May 2011

hi..actuallly i need matlab code for the design of IIR filter i.e to find magnitude and group delay of low pass butterworth filter using genetic algorithm....thanks..reply me on my email gurleensohi@gmail.com

Walter Roberson

### Walter Roberson (view profile)

on 14 May 2011

Please start a new question for that topic.

Log in to comment.

### Navneet kaur (view profile)

Answer by Navneet kaur

### Navneet kaur (view profile)

on 6 Oct 2016

have you come to know how to remove this error?? @yasmine

Walter Roberson

### Walter Roberson (view profile)

on 6 Oct 2016

Your objective function should be whatever you want minimized. It will take a vector of input values and must output a scalar score, lower is more "fit".

Log in to comment.

### Awais khan (view profile)

Answer by Awais khan

### Awais khan (view profile)

on 15 Oct 2016
Edited by Walter Roberson

### Walter Roberson (view profile)

on 15 Oct 2016

```%problem is to maximize x^2 in 0 and 16 range
%%popsize=5
popsize=6;
POP=round(rand(popsize,4))
```
```%%evaluation of the fitness funcs.
for iteration=1:1000
for ii=1:popsize
f(ii)=(bin2dec(num2str(POP(ii, :))))^2;
end
```
```      for ii=1:popsize
contribution(ii)=f(ii)/sum(f);
end
contribution;
contribution=contribution* popsize
contribution=round( contribution)
%pause
if sum(contribution)>popsize
[mymax,myindex]=max( contribution)
contribution(myindex)= contribution(myindex)-1
if sum(contribution)>popsize
[mymax,myindex]=max( contribution)
contribution(myindex)= contribution(myindex)-1
end
%pause
end
if sum(contribution)<popsize
[mymax,myindex]=max( contribution)
contribution(myindex)= contribution(myindex)+1
if sum(contribution)<popsize
[mymax,myindex]=max( contribution)
contribution(myindex)= contribution(myindex)+1
end
%pause
end%%BURAYI DUZELTELIM
%myindexes=contribution```
```      %%Elements to be crossovered
POP
pause
m=1;
for ii=1:popsize
if contribution(ii)>0
gett=contribution(ii);
for jj=1:gett
TOCR(m,:)=POP(gett,:);
m=m+1;
end
end
end
myrandperms=randperm(popsize);
TOCR
111
pause
TOCR=TOCR(myrandperms,:)
% pause
CR=0.7;
%%CROSSOVER %let crossover point be 2
for ii=1:2:popsize-1
myrand=rand;
if myrand<CR```
```              temp1=TOCR(ii,3:4);
temp2=TOCR(ii+1,3:4);
TOCR(ii,3:4)=temp2;
TOCR(ii+1,3:4)=temp1;```
```          end
end
PM=0.1;
%%MUTATION
for ii=1:popsize
for jj=1:4%%number of bits
myrand=rand;
if myrand<PM
TOCR(ii,jj)=TOCR(ii,jj)+1;
TOCR(ii,jj)=rem(TOCR(ii,jj),2) ;
end
end
end
POP=TOCR;
end
POP```

I have some errors in this code and cannot fix, How can i fix these errors to run my code

#### 0 Comments

Log in to comment.

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today