assigning a probability to a loop
20 views (last 30 days)
Show older comments
Hello,
I am making a random walk code, and I want to assign a probability to the direction chosen. I found a way to do this with IF loops, as in the code below, using the variable J:
x=2; %starting poition in X and Y
y=3;
v=50; %number of steps
X=[];
Y=[];
X(1)= x;
Y(1)= y;
for i=1:v
J=rand; % Random value to decide on direction.
if J<0.3 % Go North
X(i+1)=X(i)+1;
Y(i+1)=Y(i);
elseif (J>0.3) && (J<0.45) % Go NW
X(i+1)=X(i)+1;
Y(i+1)=Y(i)-1;
elseif (J>0.45) && (J<0.6) %Go NE
X(i+1)=X(i)+1;
Y(i+1)=Y(i)+1;
elseif (J>0.6) && (J<0.7) % Go East
X(i+1)=X(i);
Y(i+1)=Y(i)+1;
elseif (J>0.7) && (J<0.8) % Go West
X(i+1)=X(i);
Y(i+1)=Y(i)-1;
elseif (J>0.80) && (J<0.875) % Go SE
X(i+1)=X(i)-1;
Y(i+1)=Y(i)+1;
elseif (J>0.875) && (J<0.95) % Go SW
X(i+1)=X(i)-1;
Y(i+1)=Y(i)-1;
else %Go south
X(i+1)=X(i)-1;
Y(i+1)=Y(i);
end
plot (X, Y)
end
I am wondering if there is an easier way to assign a probability of an event happening. Ideally I'm looking for a way to just enter a %. e.g:
for i=1:v
In 30% of cases, do this: %North
X(i+1)=X(i)+1;
Y(i+1)=Y(i);
In 15% of cases, do this: % Go NW
X(i+1)=X(i)+1;
Y(i+1)=Y(i)-1;
and so on.
Thank you.
0 Comments
Accepted Answer
Walter Roberson
on 23 Nov 2011
Create your probability vector with the per-state probabilities, and then cumsum() the vector to get the boundaries for the range rand() has to fall in.
If you want, you could combine that with a find() to determine the state number, and then switch on the state number rather than on the probabilities.
0 Comments
More Answers (1)
See Also
Categories
Find more on Quadratic Programming and Cone Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!