Help with for loops

2 vues (au cours des 30 derniers jours)
Thomas Stolpe
Thomas Stolpe le 24 Sep 2018
Réponse apportée : Jan le 24 Sep 2018
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)

Réponses (1)

Jan
Jan le 24 Sep 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)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by