assigning a probability to a loop

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.

 采纳的回答

Walter Roberson
Walter Roberson 2011-11-23

0 个投票

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.

类别

帮助中心File Exchange 中查找有关 Quadratic Programming and Cone Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by