MATLAB: I need to simulate a random walk in 10000 steps in 2-dimensions of ‘x’ and ‘y’ in the positive and negative directions of the axis. And plot the walk simulation.

for loopif statementplotplottingrandi functionrandom walksave valuessimulation

The problem I have with my code is that it keeps assign the X and Y values to zeros and doesn't plot the 10000 values of X and Y. Here is the code:
R = randi([1,4],10000,1);
for i=1
X(i)=0;
y(i)=0;
end
for i=1:10000;
if R == 1
X(i) = X(i)+1;
elseif R == 2
X(i) = X(i)-1;
elseif R == 3
y(i) = y(i)+1;
elseif R == 4
y(i) = y(i)-1;
end
end
plot(X,y);
comet(X,y)
grid on;

Best Answer

Your R is a column vector of length 10000 .
You have the statement
if R == 1
This is equivalent to
if all(R == 1)
which is extremely likely to be untrue.
You should be indexing R in your loop: R(i) each time.
Note: it is also advisable to pre-allocate all of x and y. You would do that by changing
for i=1
X(i)=0;
y(i)=0;
end
to
X = zeros(10000,1);
Y = zeros(10000,1);