Skip to content

Instantly share code, notes, and snippets.

@grantmwilliams
Last active August 29, 2015 14:18
Show Gist options
  • Save grantmwilliams/1d76bcb28a72f34838b1 to your computer and use it in GitHub Desktop.
Save grantmwilliams/1d76bcb28a72f34838b1 to your computer and use it in GitHub Desktop.
%% Standard Genetic Algorithm -- Solves For A User Input String
clear;close all;clc; %Clears variables, closes windows, and clears the command window
tic % Begins the timer
%% Select Target String
target = 'Hello, world!';
% *Can Be Any String With Any Values and Any Length!*
%% Parameters
popSize = 1000; % Population Size (100-10000 generally produce good results)
genome = length(target); % Genome Size
mutRate = .01; % Mutation Rate (5%-25% produce good results)
best = Inf; % Initialize Best (arbitrarily large)
MaxVal = max(double(target)); % Max Integer Value Needed
ideal = double(target); % Convert Target to Integers
%% Initialize Population
Pop = round(rand(popSize,genome)*(MaxVal-1)+1); % Creates Population With Corrected Genome Length
for Gen = 1:1e6 % A Very Large Number Was Chosen, But Shouldn't Be Needed
%% Fitness
F = sum(abs(bsxfun(@minus,Pop,ideal)),2);
if (min(F) == 0)
[~,idx] = sort(F);
break
end
%% Selection - 50% Truncation
[~,V] = sort(F,'descend'); % Sort Fitness in Ascending Order
V = V(popSize/2+1:end); % Winner Pool
W = V(round(rand(2*popSize,1)*(popSize/2-1)+1))'; % Winners
%% Crossover - 2 point
Pop2 = Pop(W(1:2:end),:); % New Pop is Winners of old Pop
P2A = Pop(W(2:2:end),:); % Assemble Pop2 Winners 2
Ref = ones(popSize,1)*(1:genome); % Ones Matrix
CP = sort(round(rand(popSize,2)*(genome-1)+1),2); % Crossover Points
idx = CP(:,1)*ones(1,genome)<Ref&CP(:,2)*ones(1,genome)>Ref; % Index
Pop2(idx)=P2A(idx); % Recombine Winners
%% Mutation
idx = rand(size(Pop2))<mutRate; % Index of Mutations
Pop2(idx) = round(rand([1,sum(sum(idx))])*(MaxVal-1)+1); % Mutated Value
%% Reset Poplulations
Pop = Pop2;
end
toc % Ends timer and prints elapsed time
disp('Best Fitness: ');
disp(min(F));
disp('Best Genome: ');
disp(char(Pop(idx(1),:)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment