vectorize random walk displacement function

조회 수: 2 (최근 30일)
Luis Isaac
Luis Isaac 2019년 4월 17일
답변: Walter Roberson 2019년 4월 17일
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

답변 (1개)

Walter Roberson
Walter Roberson 2019년 4월 17일
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.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by