Matlab 在循环中的点之间绘制直线出错

Matlab 在循环中的点之间绘制直线出错,matlab,Matlab,我目前正在尝试模拟随机行走。想法是在0和2*pi之间选择一个随机数,让随机游走者朝这个方向走。下面是我试图模拟这种随机行走的步骤: before=[0 0]; %start in (0,0) while 1 x=rand; x=x*2*pi; %// choose random angle increment=[cos(x),sin(x)] %// increments using the sine and cosine function now=before+i

我目前正在尝试模拟随机行走。想法是在
0
2*pi
之间选择一个随机数,让随机游走者朝这个方向走。下面是我试图模拟这种随机行走的步骤:

before=[0 0]; %start in (0,0)
while 1
    x=rand;
    x=x*2*pi; %// choose random angle
    increment=[cos(x),sin(x)] %// increments using the sine and cosine function
    now=before+increment;
    plot(before, now)
    hold on
    before=now;
    pause(1);
end

我希望这个程序能够绘制线条,每一条新线都从前一行的终点开始,但这并没有发生。我不知道它为什么不起作用。

你把
plot
的语法搞错了,就是
plot(X,Y)
。把电话改成

plot([before(1), now(1)], [before(2), now(2)])

你的程序应该能按预期工作。

你把
plot
的语法搞错了,这就是
plot(X,Y)
。把电话改成

plot([before(1), now(1)], [before(2), now(2)])

您的程序应该能按预期工作。

这里有一个改进版,它可以执行所有矢量化的计算,并提供两种输出选择。第一个一次显示所有内容,速度非常快。第二种方法需要大量的时间,这取决于样本的数量

pts = [0,0];                % starting point
N   = 10000;                % sample count
x   = rand(N,1) * 2*pi;     % random angle

% calculate increments and points
inc = [cos(x),sin(x)];
pts = [pts;cumsum(inc,1)];

% plot result at once
figure;
plot(pts(:,1),pts(:,2));

% plot results in time steps
figure; hold on;
for i = 1:size(pts,1)
    plot(pts(i:i+1,1),pts(i:i+1,2))
    pause(1)
end
以下是一个输出示例:

这是一个改进版,它将所有计算矢量化,并为您提供两种输出选择。第一个一次显示所有内容,速度非常快。第二种方法需要大量的时间,这取决于样本的数量

pts = [0,0];                % starting point
N   = 10000;                % sample count
x   = rand(N,1) * 2*pi;     % random angle

% calculate increments and points
inc = [cos(x),sin(x)];
pts = [pts;cumsum(inc,1)];

% plot result at once
figure;
plot(pts(:,1),pts(:,2));

% plot results in time steps
figure; hold on;
for i = 1:size(pts,1)
    plot(pts(i:i+1,1),pts(i:i+1,2))
    pause(1)
end
以下是一个输出示例: