2017-02-27 165 views
0
clear all 
%heads>=0.5 %tails<0.5 
for i=1:500 
    coin=rand(1,2);  
    A=[coin]; 
    toss=1; 
while coin(1)<.5 
    coin=rand(1,2); 
    B=[coin]; 
    toss=1+tossr; 
    A=[A;B]; 
    C=[toss]; 
end 
fprintf('Number of toss to obtain head %.0f \n',toss) 
end 

我該如何做所有折騰的頻率向量?投幣模擬

我要讓所有的投擲的頻率表

enter image description here

+1

如果您需要500次投擲,爲什麼不生成一個大小爲500的隨機向量? –

回答

0

Soltion使用randi

clearvars 
toss=0; 

for i=1:500 
    if randi(2)==1 %1 for tails, 2 for heads 
     toss=toss+1; 
    else 
     FreqToss(i)=toss; 
     fprintf('Number of toss to obtain head %.0f \n',toss) 
     toss=0; 
    end 
end 
0

檢查,這是一個簡單的解決方案:

clear; clc; close; 
toss=0; 
Tossvector=[]; 

%heads>=0.5 %tails<0.5 
for i=1:500 
    coin=rand();  
    if coin <.5 
     toss=toss+1; 
     Tossvector=horzcat(Tossvector,toss); 
    end 
    if coin >.5 
     fprintf('Number of toss to obtain head %.0f \n',toss) 
     toss=0; 
    end 
end