1

嗨,我正在研究我的第一个随机游走程序。我只是能够弄清楚随机游走程序本身。这是一个简单的一维随机游走,有 1000 步。这是我的代码到目前为止的样子:

stepslim = 1000;
rnew(1) = 0
r=0;
%Now we will set up the for loop
for isteps = 2:1:stepslim;
    if rand <= 0.5             %The if-else statement will tell the walker
        step = -1;             %which direction it steps in
    else
        step = +1;
    end
    rnew(isteps) = rnew(isteps-1) + step; %This adds the new step
end
plot(rnew); %This will plot our random walk

这工作得很好,现在我需要尝试更多的任务:

  • 运行此模拟 X 次以生成一个集成。在集合中的每个模拟结束时记录/存储步行者的最终位置。

  • 为合奏中的每个模拟生成步行者结束位置的直方图 ▪ 调整 bin-width 以“理解”您的结果。

  • 重复并绘制 X = [1000, 2000, 10000, 20000, 100000, 1000000] 的结果

我不确定如何重复模拟并将结束值记录到一个集合中。在完成这些任务时,我将不胜感激

4

1 回答 1

1

您生成随机游走的方法非常、非常、非常缓慢……如果您想更改方法,我建议您改用以下代码:

steps = 1000;
rw = cumsum(-1 + 2 * round(rand(steps,1)),1);

从这一点开始,您可以通过以下方式运行模拟x时间、记录每个结果并检索每个模拟的最后一步:

iters = 10;
steps = 1000;

rws = NaN(steps,iters);

for i = 1:iters
    rws(:,i) = cumsum(-1 + 2 * round(rand(steps,1)),1);
end

% retrieve the last step
last_steps = rws(end,:);

为了绘制最后一步的直方图,您可以使用histogram足够灵活的函数来打印与您的数据足够一致的内容:

histogram(last_steps);

要使用不同的步长,只需将所有内容都包含在另一个for loop中,您可以在其中循环您在数组中定义的每个步长:

X = [1000, 2000, 10000, 20000, 100000, 1000000];

for j = 1:numel(X)
    % previous code with variable "steps" replaced by X(j)
end
于 2017-12-01T00:04:09.817 回答