How to do a Population and crossover on matrix ?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
How to generate a 20 population of matrix and then calculate fitness funtion to eaach one using sum (sum (matrix)) then perform a random selection of parents among the 10 min value of matrix then do the crossover on them ??? And after that a randomly mutation
To achieve the minimum fitness Using matlab
0 comentarios
Respuestas (1)
Shishir Reddy
el 30 de Mayo de 2025
As per my understanding, you would like to Implement a genetic algorithm in MATLAB to minimize the sum of matrix elements by evolving a population of random matrices using selection, crossover, and mutation.
Kindly refer to the following steps for the same -
1. Set Parameters and Generate Initial Population
clc;
clear;
% Parameters
pop_size = 20; % Total number of matrices
matrix_size = [5, 5]; % Size of each matrix
num_generations = 50; % Number of generations to evolve
mutation_rate = 0.1; % Probability of mutation (10%)
% Initialize population with random integers from 0 to 10
population = cell(pop_size, 1);
for i = 1:pop_size
population{i} = randi([0, 10], matrix_size);
end
2. Evaluate Fitness for Each Matrix and Select the Top 10 Fittest Matrices
for gen = 1:num_generations
% Compute fitness (lower is better)
fitness = zeros(pop_size, 1);
for i = 1:pop_size
fitness(i) = sum(sum(population{i}));
end
% Select 10 matrices with the lowest fitness
[~, idx] = sort(fitness); % Sort indices by fitness
top10 = population(idx(1:10)); % Select best 10
3. Generate New Population via Crossover and Mutation
new_population = cell(pop_size, 1);
for i = 1:2:pop_size
% Randomly select two parents from top 10
p1 = top10{randi([1, 10])};
p2 = top10{randi([1, 10])};
% Crossover: combine rows from both parents
crossover_point = randi([1, matrix_size(1)-1]);
child1 = [p1(1:crossover_point, :); p2(crossover_point+1:end, :)];
child2 = [p2(1:crossover_point, :); p1(crossover_point+1:end, :)];
% Mutation: randomly change one element in each child with a small chance
if rand < mutation_rate
row = randi([1, matrix_size(1)]);
col = randi([1, matrix_size(2)]);
child1(row, col) = randi([0, 10]);
end
if rand < mutation_rate
row = randi([1, matrix_size(1)]);
col = randi([1, matrix_size(2)]);
child2(row, col) = randi([0, 10]);
end
% Add children to new population
new_population{i} = child1;
if i+1 <= pop_size
new_population{i+1} = child2;
end
end
4. Update Population and Print Progress
% Replace the old population with the new one
population = new_population;
% Print best fitness in this generation
best_fit = min(cellfun(@(m) sum(sum(m)), population));
fprintf('Generation %d - Best Fitness: %d\n', gen, best_fit);
end
I hope this helps.
0 comentarios
Ver también
Categorías
Más información sobre Genetic Algorithm en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!