Info

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

Loop Confusion while referencing random values

1 view (last 30 days)
Sumara
Sumara on 9 Jun 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
I have a code that
  1. randomly generates values between 0 and1
  2. The value is then referenced into percent weight table and generates an integer between 1 and 10
  3. it then states whether the integer generated is located in set1 set2 or set3
I would like this code to loop and continue producing the random values between 0 and 1 until the integer generated in step 2 is located in set1
Sets 1 2 and 3 do not contain matching values, but do contain all values 1-10
Step 2 only generates values between 1 and 10, so every integer generated is located in only one of the 3 sets of values
Value = rand;
Low = Value<=percentweight; %This compares the generated value to the table
value2 = Table{end-sum(Low),integer}; %This utilizes the comparison to select the correct integer for the generated value
1 = sum(value2 == Set1); %1,2,and3 compare the integer selected to three separate sets of values
2 = sum(value2 ==Set2);
3 = sum(value2 == Set3);
  1 Comment
Geoff Hayes
Geoff Hayes on 9 Jun 2019
Jillyn - what is your intent with the code
1 = sum(value2 == Set1);
Are you trying to compare the value to one? Or are you trying to assign the result to a variable? Please note that variable names must begin with a letter (see naming variables for details). You may want to rename the variables as
inSet1 = sum(value2 == Set1); %1,2,and3 compare the integer selected to three separate sets of values
inSet2 = sum(value2 == Set2);
inSet3 = sum(value2 == Set3);
I'm not sure where in your code you update the three different sets, but you probably want a loop something like the following
maxIterations = 1000;
for k = 1:maxIterations
Value = rand;
Low = Value<=percentweight; %This compares the generated value to the table
value2 = Table{end-sum(Low),integer}; %This utilizes the comparison to select the correct integer for the generated value
inSet1 = sum(value2 == Set1); %1,2,and3 compare the integer selected to three separate sets of values
inSet2 = sum(value2 == Set2);
inSet3 = sum(value2 == Set3);
if inSet1
break;
end
end
So we exit the loop if the integer is in the first set (i.e. inSet1 is true).

Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!