How do I make a 2D randomwalk?

34 visualizaciones (últimos 30 días)
Delshad Ayoubi
Delshad Ayoubi el 17 de Feb. de 2018
Comentada: Image Analyst el 1 de Mzo. de 2022
I have so far only been able to make a 1D randomwalk but I have to make it into 2D. Below is my code for 1D. How do I change it so that it is in 2D?
clear
clc
N = 100; % Length of the x-axis, also known as the length of the random walks.
M = 400; % The amount of random walks.
x_t(1) = 0;
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;
end
plot(x_t);
hold on
end

Respuesta aceptada

Image Analyst
Image Analyst el 17 de Feb. de 2018
Editada: Image Analyst el 17 de Feb. de 2018
Just duplicate everything for y:
clc;
clearvars;
N = 100; % Length of the x-axis, also known as the length of the random walks.
M = 400; % The amount of random walks.
x_t(1) = 0;
y_t(1) = 0;
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); % Generates either +1/-1 depending on the SIGN of RAND.
y_t(n+1) = y_t(n) + A;
end
plot(x_t, y_t);
hold on
end
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.05, 1, 0.95]);
axis square;
For what it's worth, see my attached random walk demos.
  13 comentarios
Andy Paulo Ureña
Andy Paulo Ureña el 1 de Mzo. de 2022
Hi, how can i calculate the distance from the origin to all points taken in every step iteration? Thanks a lot
Image Analyst
Image Analyst el 1 de Mzo. de 2022
@Andy Paulo Ureña make a new array called allDistances, and assign it distances
allDistances(n) = distance;

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by