如何在 MatLab 中重复随机游走模拟并记录最终结果?
How to repeat random walk simulation and record end results in MatLab?
您好,我正在研究我的第一个随机游走程序。我刚刚能够弄清楚随机游走程序本身。这是一个简单的一维随机游走,有 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 次以生成一个集成。 Record/store 整体中每次模拟结束时步行者的最终位置。
为整体中的每个模拟生成步行者结束位置的直方图 ▪ 调整 bin 宽度以“理解”您的结果。
重复并绘制 X = [1000, 2000, 10000, 20000, 100000, 1000000]
的结果
我不确定如何重复模拟并将最终值记录到合奏中。如果能帮我完成这些任务,我将不胜感激
你生成随机游走的方法非常、非常、非常慢...如果你想改变你的方法,我建议你改用下面的代码:
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
您好,我正在研究我的第一个随机游走程序。我刚刚能够弄清楚随机游走程序本身。这是一个简单的一维随机游走,有 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 次以生成一个集成。 Record/store 整体中每次模拟结束时步行者的最终位置。
为整体中的每个模拟生成步行者结束位置的直方图 ▪ 调整 bin 宽度以“理解”您的结果。
重复并绘制 X = [1000, 2000, 10000, 20000, 100000, 1000000]
的结果
我不确定如何重复模拟并将最终值记录到合奏中。如果能帮我完成这些任务,我将不胜感激
你生成随机游走的方法非常、非常、非常慢...如果你想改变你的方法,我建议你改用下面的代码:
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