Help with for loops
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
There is 1 box
50/50 chance for a red ball and green ball in the box to be randomly pulled out.
So the box has an equal number of red and green balls.
My question is, how do i make a loop that picks 3 balls with 50/50 chance (the ball is put back before picking the next ball, so the second and third pick are still 50/50 as well).
Specifically using fprintf to get something like: "2 red balls and 1 green ball was chosen"
I know i used disp(""), but i am a little lost on that part as well
But as of now, I just need my results to output a matrix that says:
[3 0] or [2 1] or [1 2] or [0 3]
%
%
% Here is my noob attempt
ball = rand;
for i = 1:3
if ball > 0.5
result1 = [(i+1),i];
else % ball <= 0.5
result1 = [i,(i+1)];
end
end
disp(results)
0 Commenti
Risposte (1)
Jan
il 24 Set 2018
In result1 = [(i+1),i] you overwrite result1 repeatedly instead of accumulating the results. A solution would be:
result = [];
for i = 1:3
...
result = [result, i];
...
But this would not count the red and green balls. Better:
red = 0;
green = 0;
for i = 1:3
if rand > 0.5 % Inside the loop, not once before the loop
red = red + 1
...
You can either collect the green balls also, or use the fact, that the number of red and green balls must be 3.
Finally fprintf() helps:
fprintf('Red balls: %d\n', red)
0 Commenti
Vedere anche
Categorie
Scopri di più su Get Started with MATLAB in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!