Solving probability problems with MATLAB
9 views (last 30 days)
Show older comments
How can I simulate this question using MATLAB?
Out of 100 apples, 10 are rotten. We randomly choose 5 apples without replacement. What is the probability that there is at least one rotten?
0 Comments
Answers (3)
Walter Roberson
on 15 Dec 2022
SampleSize = 100;
NumBad = 10;
NumTrials = 10000;
[~, randomized] = sort(rand(SampleSize, NumTrials), 1);
num_bad_in_first_five = sum(randomized(1:5,:) <= 10, 1);
bar(num_bad_in_first_five); title('number bad per trial')
counts = accumarray(num_bad_in_first_five.' + 1, 1, [6 1]);
bar(0:5, counts ./ NumTrials * 100); title('% of samples with exactly this many bad apples')
percent_with_at_least_one_bad = 100 - 100*(counts(1)/NumTrials)
2 Comments
Paul Hoffrichter
on 16 Dec 2020
You can simulate this problem using a Monte Carlo Simluation.
Here's a probablity MATLAB video:
How to Make Predictions Using Monte Carlo Simulations
0 Comments
Pat Gipper
on 18 Dec 2020
Here is my take using a for loop. I wouldn't mind seeing how it is done without using a for loop
%% MonteCarloBadApples.m
% Author: Pat Gipper
% Out of 100 apples, 10 are rotten. We randomly choose 5 apples without
% replacement. What is the probability that there is at least one rotten?
n=10000;% Start with 10,000 trials
x=[ones(1,10),zeros(1,90)];% 1st 10 apples are rotten, remaining 90 are OK
p=0;% Accumulator
%
for i=1:n
j=randperm(100);% Generate a random order of the indexes
y=x(j);% Randomly scatter the 10 rotten apples in the group of 100
z=sum(y(1:5))>0;% Is there a rotten apple in a group of 5?
p=p+z;% Increment the Monte-Carlo count for this trial if a bad apple turned up
end
p=p/n;% Calculate the probability from the n trials
3 Comments
Walter Roberson
on 15 Dec 2022
%% MonteCarloBadApples.m
% Author: Pat Gipper
% Out of 100 apples, 10 are rotten. We randomly choose 5 apples without
% replacement. What is the probability that there is at least one rotten?
n=10000;% Start with 10,000 trials
x=[ones(1,10),zeros(1,90)];% 1st 10 apples are rotten, remaining 90 are OK
p=0;% Accumulator
%
for i=1:n
j=randperm(100);% Generate a random order of the indexes
y=x(j);% Randomly scatter the 10 rotten apples in the group of 100
z=sum(y(1:5))>0;% Is there a rotten apple in a group of 5?
p=p+z;% Increment the Monte-Carlo count for this trial if a bad apple turned up
end
p=p/n;% Calculate the probability from the n trials
whos p
You can see that the result is a scalar. There is nothing useful to plot about a scalar.
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!