How to similuate a coin flip with probablility p
98 次查看(过去 30 天)
显示 更早的评论
How do I simulate getting a result, either 0 or 1, with probability p. So if p=0.5 I should get an output of 0 half of the time, and 1 half of the time.
1 个评论
采纳的回答
Wayne King
2011-11-9
100 tosses with p=0.5.
x = round(rand(100,1));
If you want a probability other than p=0.5, then realize that rand() is uniform random number generator between [0,1], so you can assign the output of rand() accordingly. For example, for p=0.25:
y = zeros(100,1);
x = rand(100,1);
y(x<0.25) = 1;
Or if you just want to simulate the number of 0's or 1's in a certain number of trials. Say 100 for example. Here is a simulation of ten such experiments. Requires Statistics Toolbox.
R = binornd(100,0.5,10,1);
0 个评论
更多回答(3 个)
Nick
2011-11-9
Alternatively you could use the randi function in MATLAB which generates random integers.
100 tosses with 0=heads, 1=tails
coin=randi([0:1], [100,1])
It should more or less give you 50 0's and 50 1's.
If there is more than 2 possible outcomes and they all occur with the same probability then just increase the integer range of the randi function.
4 个评论
Image Analyst
2021-11-13
编辑:Image Analyst
2021-11-13
@Evangelia Lo, if you have the Image Processing Toolbox you can use bwareafilt() to extract runs of only the length you want and then bwlabel() or regionprops() to count them. If you want to find the index where each run starts, use regionprops():
coins = logical(randi([0, 1], 1, 30000)); % 30,000 coins
patternLength = 10; % Whatever you want
% Throw out all regions that don't match the length we want using bwareafilt(). Need to invert.
coins2 = bwareafilt(~coins, [patternLength, patternLength]);
% Count them
props = regionprops(coins2, 'PixelIdxList');
numPatternOccurrences = numel(props)
% For fun, find out where they occur.
indexes = vertcat(props.PixelIdxList); % All 10 indexes in a run
startingIndex = indexes(1 : patternLength : end) % Just the starting index.
Cory London
2018-11-15
This code is easily minupulated and works pretty well
Ntoss = 100;
x = rand(1, Ntoss); % what is the resulting size of x?
toss = (x < 0.5);
SARATHRAJ V
2021-2-20
Ntoss = 100; x = rand(1, Ntoss); % what is the resulting size of x? toss = (x < 0.5);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!