Reputation: 2403
There is a two-dimensional random walk that one can find here which works perfectly in Octave. However, when I tried to write a one-dimensional random walk program, I got an error. Here is the program:
t=[];
x=[];
for i=1:100000
J=rand;
if J<0.5
x(i+1)=x(i)+1;
t(i+1)=t(i)+1;
else
x(i+1)=x(i)-1;
t(i+1)=t(i)+1;
end
end
plot(t,x)
Here is the error:
error: A(I): index out of bounds; value 1 out of bound 0
Thank you.
Upvotes: 0
Views: 173
Reputation: 112669
No need for a loop:
N = 100000;
t = 1:N;
x = cumsum(2*(rand(1,N)<.5)-1);
plot(t,x)
For the 2D case you could use the same approach:
N = 100000;
%// t = 1:N; it won't be used in the plot, so not needed
x = cumsum(2*(rand(1,N)<.5)-1);
y = cumsum(2*(rand(1,N)<.5)-1);
plot(x,y)
axis square
Upvotes: 4
Reputation: 4336
In the first iteration, i = 1
, you have x(2) = x(1) +or- 1
while x
has dimension of zero. You should define the starting point for x
and t
, which is usually the origin, you can also change the code a little bit,
x = 0;
N = 100000;
t = 0 : N;
for i = 1 : N
x(i+1) = x(i) + 2 * round(rand) - 1;
end
plot(t,x)
Upvotes: 1
Reputation: 1104
You get an error because you ask MATLAB to use x(1)
in the first iteration when you actually defined x
to be of length 0. So you need to either initialize x
and t
with the proper size:
x=zeros(1,100001);
t=zeros(1,100001);
or change your loop to add the new values at the end of the vectors:
x(i+1)=[x(i) x(i)+1];
Upvotes: 2
Reputation: 130
Since t and x are empty, therefore, you cannot index them through x(i+1) and x(i). I believe you should intialize x and t with all zeros.
Upvotes: 1