MatLab 为什么我的随机漫步机不会在捕获区内中断?

MatLab Why won't my random walker break in a capture zone?

您好,我编写了一个 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 步,但它仍然保持 运行ning。感谢任何帮助。

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

首先是这个问题:rw 是一个 1000x1 的数组。所以你的 if 语句条件 rw >= 13 & rw <= 18 同样会 return 一个 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));