MATLAB: Multiple simulation runs for random walk

for loopMATLAB

I am having trouble running multiple simulations of a random walk situation. Although I have put it into a for loop, I am having trouble making it work.
n = 10001;
for k = 1:n
result = zeros(n,1);
for z = 2:1001
w = rand(1001,1);
if (w(z) >= .5)
Left(z) = Left(z-1) + 1;
Right(z) = Right(z-1);
else
Right(z) = Right(z-1) + 1;
Left(z) = Left(z-1);
end
end
Y = Left - Right;
end
result(k) = Y;
I previously got help with this not too long ago, and I was told to put the assignment for the result in the outer for loop, but then I started getting different issues with result(k) and Y not being the same size. It would be great if I could get an explanation of how to fix this.

Best Answer

I have read your previous question, there @Walter sir suggested to keep the result within the outer loop, as follows, still if you face the issue, let me know
n = 10001;
for k = 1:n
result = zeros(n,1);
for z = 2:1001
w = rand(1001,1);
if (w(z) >= .5)
Left(z) = Left(z-1) + 1;
Right(z) = Right(z-1);
else
Right(z) = Right(z-1) + 1;
Left(z) = Left(z-1);
end
end
Y = Left - Right;
result(k) = Y;
end
Related Question