Effacer les filtres
Effacer les filtres

vectorize random walk displacement function

2 vues (au cours des 30 derniers jours)
Luis Isaac
Luis Isaac le 17 Avr 2019
Dear
I would like to code a random walk
As a part of the program the routine call a function that calculate +/-1 in one of the three coordinates for all of the n particles the program follow
This function is as follows:
function rndDesp=RandDesp(n)
rndV=randi(6,n,1);
rndDesp=zeros(n,3);
for j=1:n
if rndV(j)==1 rndDesp(j,1)=1;
elseif rndV(j)==2 rndDesp(j,1)=-1;
elseif rndV(j)==3 rndDesp(j,2)=1;
elseif rndV(j)==4 rndDesp(j,2)=-1;
elseif rndV(j)==5 rndDesp(j,3)=1;
elseif rndV(j)==6 rndDesp(j,3)=-1;
end
end
end
The result is a vector rndDesp witch have n rows (one for each particle) and three columns witch have two zeros and one +/-1 obiously in the direction (x,y,z) where the random displacement have to be taken.
The number of n particles could be quite long, so I would like to ask if the is any way to vectorize the for-loop and the if-elseif to speed the calculation.
Thanks in advance

Réponses (1)

Walter Roberson
Walter Roberson le 17 Avr 2019
Note that particular question involved a biased random walk, and that particular comment did not deal with refusing to go back where you came from. You can look at my Answer there to see a non-vectorized technique for keeping track of "heading", which makes it easier to construct the direction logic. The non-vectorized technique can be vectorized by methods similar to what I showed in the comment I linked to, involving cumsum.

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by