MATLAB : What Is cumsum Doing In This Code?

356 views Asked by At

This is the MATLAB question given by our instructor: Image Of The Question

Here is my code for how I solved the problem. I looked at the answer key and realized that my professor used cumsum, but I cannot understand what it is actually doing in my code in regards to the probability. I have gotten the correct output, but I want to have clarification:

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)

My question is, what is cumsum actually doing to get the correct probabilities? I feel as though cumsum might even be giving me the wrong answer as I would not have used it if I wasn't told to.

2

There are 2 answers

0
Code Different On

cumsusm helps you generate weighted choice for the direction of each step.

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

To help understand the problem, let's reduce it to just two choices: left or right with probabilities of 0.2 and 0.8: Prob = [0.2 0.8]; CumProb = [0.2 1]. When you generate p as a random number between 0 to 1, the index of the first value in CumProb that is greater than p is the direction you take:

  • p = 0.1 => left
  • p = 0.2 => left
  • p = 0.3 => right
  • p = 0.4 => right
  • p = 0.5 => right, etc
0
lanpa On

your code:

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

is equal to:

CumProb = cumsum(Prob)