vectorize random walk displacement function
2 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (1 件)
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.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!