In: Mechanical Engineering
A drunk man walking simulation
A drunk man stands at origin. There is a cliff at x=10 and home at
x=-10. He takes steps randomly left and right. Each step has the
probability p of going left and q=1−p of going right.
We desire to simulate and plot 100 random trajectories for the
interval of 100 time instants. Once hit at home or cliff, a
trajectory is stopped immediately and success or dead is declared.
Otherwise, alive is declared. Obtain histograms of [success, dead,
alive] for p=0.25, 0.5, and 0.75.
alive = 0
success = 0
dead = 0
p = 0.5
for (n in 1:1000)
{
i = 0
s = 0
while (s < 10 && s > -10 && i < 100)
{
x = rbinom(1, 1, p)
if(x == 1)
s = s-1
else
s = s+1
i = i+1
}
if(s == 0)
alive = alive +1
if(s == 10)
success = success + 1
if(s == -10)
dead = dead + 1
}
barplot(c(success, dead, alive))
this code not working
i need histogram and trajectories and code of mathlab
Note: The plots generated by you maybe different as each time the code is run, different values of probability are calculated at random.
The required code is given below.
clear;
clc;
p = [0.25 0.5 0.75];
figN = 1;
for k = 1:numel(p)
alive = 0;
success = 0;
dead = 0;
for n = 1:100
figure(figN)
my_title = sprintf('p =
%.2f\n',p(k));
title(my_title)
hold on
i = 0;
s = 0;
y = 0;
while (s<10
&& s>-10 && i<100)
x = binornd(1,p(k));
if x == 1
sNew = s - 1;
plot([s sNew],[y y+1],'k-')
s = sNew;
else
sNew = s + 1;
plot([s sNew],[y y+1],'k-')
s = sNew;
end
i = i + 1;
y = y + 1;
end
if s == 0
alive = alive + 1;
elseif s == 10
success = success + 1;
elseif s == -10
dead = dead + 1;
end
end
figure(figN+1)
my_title = sprintf('p = %.2f\n',p(k));
labels = {'Success', 'Dead', 'Alive'};
bar([success, dead, alive])
title(my_title)
set(gca,'xticklabel',labels)
figN = figN+2;
end