Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

Repeating a random generator

1 view (last 30 days)
candvera
candvera on 12 Jan 2016
Closed: MATLAB Answer Bot on 20 Aug 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

Answers (1)

Stephen23
Stephen23 on 12 Jan 2016
Edited: Stephen23 on 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

This question is closed.

Community Treasure Hunt

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

Start Hunting!