How to create a random walk in 1d array
15 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I tried using this code, but it is not giving the result i am expected to get, I am trying to formulate a code that can also be used for 2d array and a 3d array. The code i have above cannot be used for 2d and 3d array.
%
num=10
y=zeros(size(num,1))
yv=rand(num,1)
trials=1:num
sum=0
for i=1:length(trials)
if yv(i)< 0.5
sum=sum+1;
else
sum=sum;
end
ver(i)=sum;
end
figure (1)
hold on
c=plot(ver,trials,'-rx')
set(c,'color','blue')
grid on
title('showing the random walk less or greater than 0')
ylabel('trials')
0 Commenti
Risposte (2)
Jos (10584)
il 1 Mag 2018
Let N be the number of steps into the random walk in X dimensions, this is a one-liner that produces the positions:
N = 500 ; % number of steps
X = 6 ; % number of dimensions
% positions, starting at (0,0,...,0)
P = cumsum(full(sparse(1:N, randi(X,1,N), [0 2*randi([0 1],1,N-1)-1], N, X))) ;
% visualisation
figure ;
hold on ;
for k=1:size(P,2),
plot(1:size(P,1),P(:,k),'.-') ;
text(size(P,1),P(end, k), sprintf(' dim %d',k)) ;
end
xlabel('Step') ;
ylabel('Position') ;
hold off ;
1 Commento
Jos (10584)
il 2 Mag 2018
I have made this code publicly available as a function on the File Exchange, for anyone interested: https://uk.mathworks.com/matlabcentral/fileexchange/67160-randomwalk
Stephan
il 1 Mag 2018
Modificato: Stephan
il 1 Mag 2018
Hi,
try this:
function ver = random_walk(number_of_tries, center)
%%function gives a random walk in 1D
%
% Input: x = random_walk(1000, 0)
%
% Output: a vector x containing the data of the
% random walk with a starting point at 0. Additionally
% the result is plotted.
%%Initialising values
%
num = number_of_tries;
yv = rand(num,1);
sum = center;
ver(1) = center;
for i = 2:num
if yv(i)< 0.5
sum = sum + 1;
else
sum = sum - 1;
end
ver(i) = sum;
end
%%Plot result
%
figure (1);
%hold on;
c=plot(ver, 1:num,'-rx');
set(c,'color','blue');
grid on;
title('showing the random walk less or greater than 0');
ylabel('trials');
end
The result should look like this:

I did not really understand the 2D / 3D variant you want. Can you explain what exactly you want to do?
Best regards
Stephan
0 Commenti
Vedere anche
Categorie
Scopri di più su Time Series in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!