Borrar filtros
Borrar filtros

Why does my random walk simulation come out so weird?

2 visualizaciones (últimos 30 días)
Kevin Nelson
Kevin Nelson el 25 de Sept. de 2023
Editada: William Rose el 25 de Sept. de 2023
Why does my graph come out so weird? I've provided the code:
clearvars
N = 1000;
M = 500;
P = cumsum(full(sparse(1:N, randi(M,1,N), [0 2*randi([0 1],1,N-1)-1], N, M))) ;
figure (2);
hold on ;
for S=1:size(P,2)
plot(1:size(P,1),P(:,S),'.-');
end
title('Random walk 2')
xlabel('#Step') ;
ylabel('Distance') ;
hold off;
I was told I'm plotting along the wrong dimension of S, but what does that mean? When I alter it, the graph either crashes or gives ,e a straight line.

Respuestas (1)

William Rose
William Rose el 25 de Sept. de 2023
Your formula introduces an increaing probability of "stay the same on each step" as M, the number of walks, grows. Is that your intent? I doubt it. Here are plots of what happ[ens with your code when N=100, and M=1, M=2, and M=5. Notice the increase in the probability of making a "step" of 0, and M grows.
You can fix it by modifying (simplifying) your cumsum() statement.
  1 comentario
William Rose
William Rose el 25 de Sept. de 2023
Editada: William Rose el 25 de Sept. de 2023
[edit: add explanation of code with and without 0 as a step option]
The line
P = cumsum(full(sparse(1:N, randi(M,1,N), [0 2*randi([0 1],1,N-1)-1], N, M))) ;
causes (M-1)/M of the random steps (which would otherwise be +1 or -1) to become zero.
Therefore, when M=1, none of the steps get reset to zero, and all steps are therefore +1 or -1. When M=5, you get 4/5=80% zeros. When M=500, as in your original example, you get 499/500=99.8% zeros. This is why your random walks look weird.
If the above behavior is not desired, and if you want random steps of -1, 0, or +1 at every time point of every walk, then do:
P=cumsum(zeros(1,M);randi([-1 1],N-1,M));
Try it. It yields a nice looking set of random walks. See below for N=300,M=20 and N=1000,M=500.
If you want only -1 or +1 steps, then do
P=cumsum([zeros(1,M);2*randi([-1 1],N-1,M)-1]); % steps: -1, +1
This set of walks spreads out a bit faster than the earlier set, since 0 is not an option.

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by