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.

 採用された回答

Star Strider
Star Strider 2019 年 9 月 26 日

1 投票

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 件のコメント

Farah Mahmood
Farah Mahmood 2019 年 9 月 26 日
How do i retrieve the indices where new values are placed?
Star Strider
Star Strider 2019 年 9 月 26 日
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 2019 年 9 月 27 日
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?
Star Strider
Star Strider 2019 年 9 月 27 日
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 2019 年 9 月 27 日
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 2019 年 9 月 27 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by