if/elseif statement with rand() falling between two values
Mostra commenti meno recenti
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?
Risposta accettata
Più risposte (1)
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
Categorie
Scopri di più su Creating and Concatenating Matrices in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!