为什么二维随机游走的一维变体不起作用?
Why does the one-dimensional variant of a 2-d random walk not work?
可以找到一种二维随机游走here which works perfectly in Octave。但是,当我尝试编写一维随机游走程序时,出现了错误。这是程序:
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)
这是错误:
error: A(I): index out of bounds; value 1 out of bound 0
谢谢。
你得到一个错误,因为你要求 MATLAB 在第一次迭代中使用 x(1)
,而实际上你将 x
定义为长度为 0。所以你需要初始化 x
t
大小合适:
x=zeros(1,100001);
t=zeros(1,100001);
或更改循环以在向量末尾添加新值:
x(i+1)=[x(i) x(i)+1];
因为t和x是空的,所以不能通过x(i+1)和x(i)来索引。
我相信你应该用全零初始化 x 和 t。
在第一次迭代中,i = 1
,您有 x(2) = x(1) +or- 1
,而 x
的维度为零。你应该定义起点为x
和t
,这通常是原点,你也可以稍微改变一下代码,
x = 0;
N = 100000;
t = 0 : N;
for i = 1 : N
x(i+1) = x(i) + 2 * round(rand) - 1;
end
plot(t,x)
不需要循环:
N = 100000;
t = 1:N;
x = cumsum(2*(rand(1,N)<.5)-1);
plot(t,x)
对于 2D 情况,您可以使用相同的方法:
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
可以找到一种二维随机游走here which works perfectly in Octave。但是,当我尝试编写一维随机游走程序时,出现了错误。这是程序:
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)
这是错误:
error: A(I): index out of bounds; value 1 out of bound 0
谢谢。
你得到一个错误,因为你要求 MATLAB 在第一次迭代中使用 x(1)
,而实际上你将 x
定义为长度为 0。所以你需要初始化 x
t
大小合适:
x=zeros(1,100001);
t=zeros(1,100001);
或更改循环以在向量末尾添加新值:
x(i+1)=[x(i) x(i)+1];
因为t和x是空的,所以不能通过x(i+1)和x(i)来索引。 我相信你应该用全零初始化 x 和 t。
在第一次迭代中,i = 1
,您有 x(2) = x(1) +or- 1
,而 x
的维度为零。你应该定义起点为x
和t
,这通常是原点,你也可以稍微改变一下代码,
x = 0;
N = 100000;
t = 0 : N;
for i = 1 : N
x(i+1) = x(i) + 2 * round(rand) - 1;
end
plot(t,x)
不需要循环:
N = 100000;
t = 1:N;
x = cumsum(2*(rand(1,N)<.5)-1);
plot(t,x)
对于 2D 情况,您可以使用相同的方法:
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