【问题标题】:MATLAB : What Is cumsum Doing In This Code?MATLAB:cumsum 在这段代码中做了什么?
【发布时间】:2014-11-15 21:48:59
【问题描述】:

这是我们的讲师给出的 MATLAB 问题:

这是我如何解决问题的代码。我查看了答案键并意识到我的教授使用了 cumsum,但我无法理解它在我的代码中关于概率的实际作用。我得到了正确的输出,但我想澄清一下:

clear; clc;

m = input('Type size of map  :  ');
totalSteps = 0;
x = 0;
y = 0;
Prob = [ 2 3 4 5 6 5 4 3 ]/32;
trials = input('Type number of trials  :  ');
CumProb = Prob;

for i = (0:length(trials));

for n = 2:length(Prob)
    CumProb(n) = CumProb(n-1) + Prob(n);
end

while abs(x)<m || abs(y)<m
    r = rand(1,1);

    if r <= CumProb(1)
        x=x+1;
    elseif r<=CumProb(2)
        x=x+1 ; y=y+1;
    elseif r<= CumProb(3)
        y=y+1;
    elseif r<=CumProb(4)
        x = x-1 ; y=y+1;
    elseif r<=CumProb(5)
        x=x-1;
    elseif r<=CumProb(6)
        x=x-1; y=y-1;
    elseif r<=CumProb(7)
        y=y-2;
    else
        x = x+1 ; x=y;
    end

    totalSteps = totalSteps+1;
end
i = i+1;
end

averagesteps = totalSteps/length(trials)

我的问题是, cumsum 实际上是在做什么来获得正确的概率?我觉得 cumsum 甚至可能给了我错误的答案,因为如果我没有被告知我就不会使用它。

【问题讨论】:

  • 问题:如果您使用Prob 而不是CumProb,您的while 循环将如何变化?你怎么知道每个随机数在什么范围内?

标签: matlab function simulation cumsum


【解决方案1】:

cumsusm 帮助您为每个步骤的方向生成加权选择。

Prob = [ 2 3 4 5 6 5 4 3 ]/32;
CumProb = cumsum(Prob);
p = rand;
Direction = find(CumProb > p,1);

为了帮助理解问题,让我们将其简化为两个选择:左或右,概率分别为 0.2 和 0.8:Prob = [0.2 0.8]; CumProb = [0.2 1]。当您将p 生成为0 到1 之间的随机数时,CumProb 中大于p 的第一个值的索引就是您采取的方向:

  • p = 0.1 => 左
  • p = 0.2 => 左
  • p = 0.3 => 对
  • p = 0.4 => 对
  • p = 0.5 => 对,等等

【讨论】:

    【解决方案2】:

    你的代码:

    CumProb = Prob;
    for n = 2:length(Prob)
        CumProb(n) = CumProb(n-1) + Prob(n);
    end
    

    等于:

    CumProb = cumsum(Prob)
    

    【讨论】:

      猜你喜欢
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 2017-07-25
      相关资源
      最近更新 更多