Help with for loops
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!