if/elseif statement with rand() falling between two values
2 views (last 30 days)
Show older comments
a I have a for loop set up for a specific number of timesteps and I have a variable that I want changing between each timestep with a value of either 1, 2, 3, or 4. However, I want all of these possible values to have different probabilities of happening.
I want there to be a 30% chance it's 1, a 25% chance its either 2, or 3, and a 20% chance it's 4. I want to use a rand() between 0-1 and set up limits in these blocks of probabilities
something like
for t = 1:20
if rand() < 0.3
e(t) = 1
elseif rand() > 0.3 & < 0.55
e(t) = 2
elseif rand() > 0.55 & < 0.8
e(t) = 3
else
e(t) = 4
end
end
This isn't how to actually do this, so how would I go about setting this up?
0 Comments
Accepted Answer
Steven Lord
on 30 Oct 2024
You could either write your code like this:
rng default % Allow both code segments to generate the same sequence of random numbers
for t = 1:20
r = rand();
if r < 0.3
e(t) = 1;
elseif r > 0.3 & r < 0.55
e(t) = 2;
elseif r > 0.55 & r < 0.8
e(t) = 3;
else
e(t) = 4;
end
end
e
Or you could use the discretize function.
rng default
r = rand(1, 20);
e = discretize(r, [0 0.3 0.55 0.8 1])
The reason what you'd written didn't work was because in this line:
% elseif rand() > 0.3 & < 0.55
You may have intended for the same random number to be used in the second comparison, but MATLAB has no way of knowing that. So that second part of the statement throws an error.
More Answers (1)
Cris LaPierre
on 30 Oct 2024
There are a few issues. the biggest is that each time you call rand, you generate a new number. It doesn't make sense to chain a bunch of it-else statements together if the value being compaired keeps changing.
Second, there are gaps in your ranges. You need to make one of your edges equal to the value.
Finally, you must write complete comparison statements. You can't apply two conditions in a single comparison.
Perhaps this:
for t = 1:20
foo = rand(1);
if foo < 0.3
e(t) = 1;
elseif foo >= 0.3 & foo < 0.55
e(t) = 2;
elseif foo >= 0.55 & foo <= 0.8
e(t) = 3;
else
e(t) = 4;
end
end
e
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!