Help with for loops

1 次查看(过去 30 天)
Thomas Stolpe
Thomas Stolpe 2018-9-24
回答: Jan 2018-9-24
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)

回答(1 个)

Jan
Jan 2018-9-24
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)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by