Need help generating GA population

I am new to GA and there is something that not clear to me. I want to generate a population of k chromosomes with each chromosome length equal to Nt. Each gene in each chromosome is randomly either a '1' or '0'. For every '1' found in a chromosome i want to assign a random number between 1 and 15 for that index position. I need help generating this population.

 Respuesta aceptada

Star Strider
Star Strider el 26 de Sept. de 2019
Try this:
InitPop = randi([0 1], k, Nt);
InitPop(InitPop == 1) = randi([1 15], 1, nnz(InitPop));
This initially creates ‘InitPop’ as a matrix of [0 1] values, tne substitutes the 1 values with integers from 1 to 15.

6 comentarios

Farah Mahmood
Farah Mahmood el 26 de Sept. de 2019
How do i retrieve the indices where new values are placed?
That requires a new line in my code:
InitPop = randi([0 1], k, Nt);
InitPop(Find1s) = randi([1 15], 1, nnz(InitPop));
[NewVals_r, NewVals_c] = find(InitPop);
The find call returns the indices of the non-zero elements in ‘InitPop’. Those are the row (‘NewVals_r’) and column (‘NewVals_c’) indices of the non-zero elements.
Farah Mahmood
Farah Mahmood el 27 de Sept. de 2019
Thanks, this gives exactly the rows and columns except i replace Find1s with InitPop==1.
I am treating each chromosome as a solution set so below is the first row (or first chromosome out of k)
0 0 0 5 0 6 5 0 0 2
so devices corresponding to positions 4,6,7,10 from the above chromosome are turned on
similarly 2 13 8 7 3 0 7 0 0 15 is the second chromosome and corresponding positions are 1,2,3,4,5,7,10
so on for the rest of k chromosomes.
I want display to read 'first subset solution' (shows 4,6,7,10)
'second subset solution' (shows 1,2,3,4,5,7,10) and so on and once GA finishes it shows the best subset.
Any ideas?
I mis-copied the code I intended to post. Should have been:
InitPop = randi([0 1], k, Nt);
InitPop(InitPop == 1) = randi([1 15], 1, nnz(InitPop));
[NewVals_r, NewVals_c] = find(InitPop);
To find the non-zero elements and present them for each row, do this before and after doing the optimisation:
[NewVals_r, NewVals_c] = find(InitPop);
RowIdx = accumarray(NewVals_r, NewVals_c, [], @(x){x});
for k1 = 1:size(InitPop,1)
rowfmt = repmat('%2d ',1,numel(RowIdx{k1}));
fprintf(['subset solution %4d (',rowfmt,')\n'],k1,sort(RowIdx{k1}))
end
This prints the indices of the non-zero elements.
Experiment with the format to get the result you want.
Farah Mahmood
Farah Mahmood el 27 de Sept. de 2019
Thanks a lot Star Strider, its doing something similar to what i wanted. Hopefully will work well with the rest of the code.
Star Strider
Star Strider el 27 de Sept. de 2019
As always, my pleasure!

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 26 de Sept. de 2019

Comentada:

el 27 de Sept. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by