# A Vectorized Version of Mutation Operator in Genetic Algorithm

As described in Wiki: “Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next. It is analogous to biological mutation. Mutation alters one or more gene values in a chromosome from its initial state. In mutation, the solution may change entirely from the previous solution. Hence GA can come to better solution by using mutation. Mutation occurs during evolution according to a user-definable mutation probability. This probability should be set low. If it is set too high, the search will turn into a primitive random search.”

So from the angle of programming language, the chromosomes could be denoted by a binary string or more general, by a binary matrix, there is a low probability p_mutation with which each single bit could be flipped (0 –> 1 or 1 –> 0). I first give the naive and basic matlab code to simulate this process and then wrote a vectorized version which I consider quite neat.

% naive basic version function matrix_mutated = mutation(matrix_original, p_mutation) % flip 0/1 matrix with probability p_mutation [n l] = size(matrix_original); matrix_mutated = matrix_original; for i = 1:n for j = 1:l if rand < p_mutation matrix_mutated(i, j) = ~matrix_mutated(i, j); end end end % end of function end

And the following is the neat and vectorized version of matlab code:

% vectorized verson function matrix_mutated = mutation(matrix_original, p_mutation) % flip 0/1 matrix with probability p_mutation [n l] = size(matrix_original); rand_matrix = rand(n, l); matrix_mutated = xor(matrix_original, rand_matrix < p_mutation); % end of function end

To summarize, I first give a naive and basic version of matlab code to implement the mutation operator in Genetic Algorithm, then I simplify the code by vectorization and give a quite neat copy of code.