MATLAB: Double for loop in a random walk. How to loop over all particles simultaneously instead of looping the amount of steps for each separate particle one at a time

beginnerfor loopsrandom walk

I currently have a script that utilizes a double for loop in order to create a random walk in 2D. It however is looping over all the steps of the random walk one particle at a time. That is, it loops over N steps for one particle, then it moves on to the M:th particle and loops it over all N. I want to loop all particles M simultaneously instead of one at a time. I don't know how to do this, tried implementing a zero vector and inserting all values of x_t and y_t in it and plotting it but it didn't work, the figure looked weird. Here is the code:
clear
clc
N = 300; % Length of the x-axis, also known as the length of the random walks.
M = 40; % The amount of random walks.
x_t(1) = 0;
y_t(1) = 0;
radie=50;
x=0;
y=0;
theta=linspace(0,2*pi);
for m=1:M
for n = 1:N % Looping all values of N into x_t(n).
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.

x_t(n+1) = x_t(n) + A;
A = sign(randn);
y_t(n+1) = y_t(n) + A;
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
while distance > radie % så att de ej passerar cirkeln.
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
x_t(n+1) = x_t(n) + A;
A = sign(randn);
y_t(n+1) = y_t(n) + A;
% Compute distance again with new values.
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
end
end
plot(x_t, y_t,'Markersize',10)
hold on
plot(x+radie*cos(theta),y+radie*sin(theta));
axis equal
end
grid on
I want all of the M particles to start moving N steps at the same time instead of looping all of N over each of the inputs M contains.

Best Answer

If you want to change the order of the loops, then your x_t and y_t need to be 2d matrices
x_t = zeros(M, N+1);
y_t = zeros(M, N+1);
for n = 1:N
for m = 1:M
distance = inf;
while distance > radie
x_t(m, n+1) = x_t(m, n) + (-1).^randi(2);
y_t(m, n+1) = y_t(m, n) + (-1).^randi(2);
distance = hypot(x_t(m, n+1), y_t(m, n+1));
end
end
end
plot(x_t, y_t, 'Markersize', 10);