Info

此问题已关闭。 请重新打开它进行编辑或回答。

Repeating a random generator

1 次查看(过去 30 天)
candvera
candvera 2016-1-12
关闭: MATLAB Answer Bot 2021-8-20
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

回答(1 个)

Stephen23
Stephen23 2016-1-12
编辑:Stephen23 2016-1-12
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

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by