sam_rox
sam_rox

Reputation: 747

Random Walk in Matlab

I am trying to create a simple random walk. This is the code that I wrote.

 n=50;
 p=0.5;

Y=zeros(n,1);
X=zeros(n,1);
X(1)=0;

for i=1:length(n)
    Y(i,1)=(rand(1)<=p);
end

for i=1:length(n)
    X(i+1)=X(i)+(2*Y(i)-1);
end
plot(1:n,X,'.-')

However, in this if I check Y, which stores the random Bernoulli variables,I get all zeroes. Why does it happen?

I get a plot like, this.
Which doesn't look like a random walk. Can someone please tell me what I am doing wrong

Upvotes: 0

Views: 580

Answers (1)

JejeBelfort
JejeBelfort

Reputation: 1663

Regarding Noel's comment, indeed the length(n) should be replaced by n and the plot function should be plot(1:(n+1),X,'.-') instead as there are n+1 elements in X. You end up with the following:

n=50;
p=0.5;

Y=zeros(n,1);
X=zeros(n,1);
X(1)=0;

for i=1:n
    Y(i,1)=(rand(1)<=p);
end

for i=1:n
    X(i+1)=X(i)+(2*Y(i)-1);
end
plot(1:(n+1),X,'.-')

The plot looks more like a random walk:

enter image description here

Upvotes: 1

Related Questions