How to create a random walk in 1d array

조회 수: 15 (최근 30일)
David Achudume
David Achudume 2018년 4월 16일
댓글: Jos (10584) 2018년 5월 2일
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')

답변 (2개)

Jos (10584)
Jos (10584) 2018년 5월 1일
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
Jos (10584)
Jos (10584) 2018년 5월 2일
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
Stephan 2018년 5월 1일
편집: Stephan 2018년 5월 1일
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

카테고리

Help CenterFile Exchange에서 Time Series에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by