Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Repeating a random generator

1 vue (au cours des 30 derniers jours)
candvera
candvera le 12 Jan 2016
Clôturé : MATLAB Answer Bot le 20 Août 2021
Hi, I'm working on a genetic algorithm that has a finite state machine. In the problem, a chromosome of length 30 represents 10 states of a FSM where each state consists of 3 digits (or genes; hence total 30 genes).
In each state, the first gene contains an integer in 1-4 while the second and third genes should contain integers in 0-9.
I have successfully declared the first 3 genes (first state), however, how would I change the following so the random declaration repeats itself 10 times, as you can see the code is only doing it for the first 3 values
TempChromosomeTest = zeros(1,30);
for i=1:10
firstState = randi([1, 4])
TempChromosomeTest(1,1) = firstState;
secondState = randi([0, 9])
TempChromosomeTest(1,2) = secondState;
thirdState = randi([0,9])
TempChromosomeTest(1,3) = thirdState;
end

Réponses (1)

Stephen23
Stephen23 le 12 Jan 2016
Modifié(e) : Stephen23 le 12 Jan 2016
You do not need a loop, it is much faster to generate all of the random values at once and assign them using indexing:
>> TempChromosomeTest = zeros(1,30);
>> TempChromosomeTest(1:3:end) = randi([1,4],1,10); % firsts
>> TempChromosomeTest(2:3:end) = randi([0,9],1,10); % seconds
>> TempChromosomeTest(3:3:end) = randi([0,9],1,10); % thirds
And you can check them using indexing too:
>> TempChromosomeTest(1:3:end) % firsts
ans =
3 1 1 4 2 1 3 1 3 1
>> TempChromosomeTest(2:3:end) % seconds
ans =
9 8 4 3 9 1 2 3 7 4
>> TempChromosomeTest(3:3:end) % thirds
ans =
6 6 0 2 4 0 2 4 2 7

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by