How to create a random walk in 1d array
15 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
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)
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Time Series 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!