2014-11-04 95 views
0
T=5; 
p=0.3; 
A=[randsample(T,1,'true'); zeros(T-1,1)]; %the first element of A is uniformly 
              %randomly drawn from {1,...,T} 

我不知道该怎么写这段代码在Matlab:伯努利过程在Matlab

%for t=2:T 
    %with probability p A(t)is A(t-1)+1 
    %with probability 1-p A(t) is uniformly randomly drawn from {1,...,T} 
%end 
+0

首先是什么问题?你有错误吗?如果是,什么是堆栈跟踪?你能把这些信息放进去吗? – ha9u63ar 2014-11-04 09:07:14

回答

1

您可以使用rand获得均匀分布的随机变量,randi获得随机整数。查阅文档以了解它们的工作方式。

此代码片段应该会对您有所帮助,它会在您的for循环内进行。我已经使用rand()<p以概率p发生某些事情,因为从0到1之间的均匀分布的随机数的概率为p小于p

if rand()<p 
    % this happens with probability p 
    A(t)=A(t-1)+1 
else 
    % this happens with probability 1-p 
    A(t)=randi(T) 
end