for n = 1:N .

A = randi(4);

rr=rand;

if rr < 1/4

A = 1+mod(A,4);

elseif rr < 1/2

A = 1+mod(A-2,4);

end

if A==1

y_t(n+1)=y_t(n)+1;%north

x_t(n+1)=x_t(n);

elseif A==2

y_t(n+1)=y_t(n)-1;

x_t(n+1)=x_t(n); %south

elseif A==3

x_t(n+1)=x_t(n)+1;%east

y_t(n+1)=y_t(n);

elseif A==4

x_t(n+1)=x_t(n)-1;%west

y_t(n+1)=y_t(n);

else

end

end

Answer by Walter Roberson
on 28 Dec 2018

Ege Tunç
on 28 Dec 2018

changes on y direction are north and south, changes on x direction east and west. Am I wrong?

Also if neutrons leaves shield any side they must continues as a straigth line.The only problem is checking last step's direction to avoid step back

Ege Tunç
on 28 Dec 2018

Walter Roberson
on 28 Dec 2018

Sign in to comment.

Answer by Image Analyst
on 28 Dec 2018

What I'd probably do is to compute all your directions in advance, and then remove disallowed ones. That way you don't have to check each one in the loop.

maxNumExpectedSteps = 100; % A million, or whatever - some big number, bigger than you expect to ever need.

directions = randi(4, 1, maxNumExpectedSteps)

% Remove elements where the next direction

% would have been in a disallowed direction.

% If it's going in direction 1, don't let it go in direction 3

% So replace the pattern [1, 3] with 1

directions = strrep(directions, [1, 3], 1);

% If it's going in direction 2, don't let it go in direction 4

% So replace the pattern [2, 4] with 2

directions = strrep(directions, [2, 4], 2);

% If it's going in direction 3, don't let it go in direction 1

% So replace the pattern [3, 1] with 3

directions = strrep(directions, [3, 1], 3);

% If it's going in direction 4, don't let it go in direction 2

% So replace the pattern [4, 2] with 4

directions = strrep(directions, [4, 2], 4);

% Now you're guaranteed to never go in a disallowed direction.

Now, start your loop getting the direction (1 through 4) from the "directions" array.

for k = 1 : numSteps

thisDirection = directions(k);

if thisDirection == 1

% Code to move in direction 1.

elseif thisDirection == 2

% Code to move in direction 2.

elseif thisDirection == 3

% Code to move in direction 3.

elseif thisDirection == 4

% Code to move in direction 4.

end

end

Ege Tunç
on 6 Jan 2019

Image Analyst
on 6 Jan 2019

Ege Tunç
on 6 Jan 2019

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Image Analyst (view profile)

Direct link to this comment:https://fr.mathworks.com/matlabcentral/answers/437516-how-to-avoid-stepping-back-on-random-2d-walker#comment_655047

Sign in to comment.