assigning a probability to a loop
Afficher commentaires plus anciens
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.
Réponse acceptée
Plus de réponses (1)
Fangjun Jiang
le 23 Nov 2011
0 votes
Catégories
En savoir plus sur Quadratic Programming and Cone Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!