0

嗨,我编写了一个 1d 随机游走器,我正在尝试实现一个捕获区域,如果游走器在特定的值范围内保持一定时间,程序将在该区域停止。我的代码如下所示:

steps = 1000; %sets the number of steps to 1000
rw = cumsum(-1 + 2 * round(rand(steps,1)),1); %Set up our random walk with cumsum

%Now we will set up our capture zone between 13-18 for fun
if rw >= 13 & rw <= 18
    dwc = dwc + 1 %Dwelling counted ticks up every time walker is in 13-18
else dwc = 0;     %Once it leaves, it returns to 0
end

while dwc >= 5
    fprintf('5 steps or more within range after %d steps, so so breaking out.\n', rw);
break
end

figure(7)
comet(rw); %This will plot our random walk
grid on;   %Just to see the capture zone better
hold on;
line(xlim, [13, 13], 'Color', 'r');
line(xlim, [18, 18], 'Color', 'r');
hold off;
title('1d Random Walk with Capture Zone');
xlabel('Steps');
ylabel('Position');

它会穿过人行道,但永远不会在捕获区中断。我确信它已经多次在捕获区域中超过 5 步,但它仍然会继续运行。任何帮助表示赞赏。

4

1 回答 1

1

你的代码没有按照你的想法做。没有循环可以逐步计算步数并检查捕获(......无论如何你都不需要循环)

首先这个问题:rw 是一个 1000x1 数组。所以你的 if 语句条件rw >= 13 & rw <= 18同样会返回一个 1000x1 逻辑。从那以后就不会赚很多了。

第二个问题是您永远不会修改循环内的 while 条件,因此它要么越过它,要么陷入无限循环。

while dwc >= 5
...
break
end

使用 now 循环编辑线性版本:

steps = 1000; %sets the number of steps to 1000
rw = cumsum(-1 + 2 * round(rand(steps,1)),1); %Set up our random walk with cumsum

%Now we will set up our capture zone between 13-18 for fun
captureCheck      = rw >= 13 & rw <= 18;

%Counts the number of consecutive steps within the capture zone.
consecStepsInZone = diff([0 (find( ~(captureCheck(:).' > 0))) numel(captureCheck) + 1])- 1;  

fprintf('The max number of consecutive steps in the zone is: %d\n',max(consecStepsInZone));
于 2017-12-01T03:19:16.207 回答