This is the MATLAB question given by our instructor:
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.
cumsusm
helps you generate weighted choice for the direction of each step.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 generatep
as a random number between 0 to 1, the index of the first value inCumProb
that is greater thanp
is the direction you take:p = 0.1
=> leftp = 0.2
=> leftp = 0.3
=> rightp = 0.4
=> rightp = 0.5
=> right, etc