if/elseif statement with rand() falling between two values

2 views (last 30 days)
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
Error using &
Not enough input arguments.
This isn't how to actually do this, so how would I go about setting this up?

Accepted Answer

Steven Lord
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
e = 1×20
4 4 1 4 3 1 1 2 4 4 1 4 4 2 4 1 2 4 3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or you could use the discretize function.
rng default
r = rand(1, 20);
e = discretize(r, [0 0.3 0.55 0.8 1])
e = 1×20
4 4 1 4 3 1 1 2 4 4 1 4 4 2 4 1 2 4 3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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.
  1 Comment
Kitt
Kitt on 30 Oct 2024
okay, that's what I was thinking was the issue because I wanted it to be the same number each time and I wasn't sure how to make sure it was the same number. Thanks!

Sign in to comment.

More Answers (1)

Cris LaPierre
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
e = 1×20
3 4 1 2 2 3 4 4 3 2 2 3 4 3 3 3 3 2 3 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Community Treasure Hunt

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

Start Hunting!