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

조회 수: 6 (최근 30일)
Kitt
Kitt 2024년 10월 30일
댓글: Kitt 2024년 10월 30일
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?

채택된 답변

Steven Lord
Steven Lord 2024년 10월 30일
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
Kitt
Kitt 2024년 10월 30일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Cris LaPierre
Cris LaPierre 2024년 10월 30일
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>

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by