How do I make a 2D randomwalk?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
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
채택된 답변
Image Analyst
2018년 2월 17일
편집: Image Analyst
2018년 2월 17일
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
Delshad Ayoubi
2018년 2월 17일
Mine looks like the one I just attached, sort of going sideways.
Image Analyst
2018년 2월 17일
편집: Image Analyst
2018년 2월 17일
I can't see the one you attached. Attach a .PNG screenshot instead. The code I gave you does produce an image like in the link you shared.

Why do you think it doesn't?
Delshad Ayoubi
2018년 2월 17일
Hmm... Maybe I'm thinking wrongly but it looks like it goes sideways instead of "up", "down" etc.
Image Analyst
2018년 2월 17일
편집: Image Analyst
2018년 2월 17일
If you limit the steps to EITHER the x direction of the y direction, but NOT BOTH, then the grid would be sideways. However, if you require that BOTH x and y change by 1, then it will look like it does. If you don't want that, then just change ONE of them, not both simultaneously. See the code below:
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.
if rand > 0.5
% Change only x.
x_t(n+1) = x_t(n) + A;
y_t(n+1) = y_t(n);
else
% Change only y.
x_t(n+1) = x_t(n);
y_t(n+1) = y_t(n) + A;
end
end
plot(x_t, y_t, 'LineWidth', 2);
hold on
end
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.05, 1, 0.95]);
axis square;

Delshad Ayoubi
2018년 2월 17일
Alright.
How do plot the position of all the particles? I tried using 'Markersize' but it doesn't seem to make them larger.
Delshad Ayoubi
2018년 2월 17일
I created a circle using linspace. How can I create code that makes all randomwalks stay within this circle? Assuming they reach the circles surface they, with the help of IF, changes to the opposite direction instead of going through the circle.
I tried making IF statement in the For-loop but they keep going through it.
Not hard. See if you can do it yourself. Just get the distance of the current point from the origin and keep trying while the distance > radius.
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
while distance > radius
% Get new trial x_t and y_t
x_t(n+1) = .......... etc.
% Compute distance again with new values.
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
end
Anyway, you're a smart engineer so I'm sure you can figure it out yourself without me telling you.
Alright, seems like you're having trouble, so here is the complete code:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
clc;
clearvars;
stepsPerWalk = 100; % Length of the x-axis, also known as the length of the random walks.
numberOfWalks = 400; % The amount of random walks.
x_t(1) = 0;
y_t(1) = 0;
% Plot a circle
radius = 20;
pos = [-radius, -radius, 2*radius, 2*radius];
rectangle('Position',pos,'Curvature',[1 1], 'LineWidth', 3)
axis equal;
ax = gca;
ax.FontWeight = 'bold';
ax.FontSize = 20;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
hold on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.05, 1, 0.95]);
% Do the random walk.
for m = 1 : numberOfWalks
for n = 1 : stepsPerWalk % Looping all values of N into x_t(n).
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
if rand > 0.5
% Change only x.
x_t(n+1) = x_t(n) + A;
y_t(n+1) = y_t(n);
else
% Change only y.
x_t(n+1) = x_t(n);
y_t(n+1) = y_t(n) + A;
end
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
while distance > radius
% Get new trial x_t and y_t
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
if rand > 0.5
% Change only x.
x_t(n+1) = x_t(n) + A;
y_t(n+1) = y_t(n);
else
% Change only y.
x_t(n+1) = x_t(n);
y_t(n+1) = y_t(n) + A;
end
% Compute distance again with new values.
distance = sqrt(x_t(n+1)^2 + y_t(n+1)^2);
end
end
plot(x_t, y_t, 'LineWidth', 2);
caption = sprintf('Walk #%d of %d', m, numberOfWalks);
title(caption, 'FontSize', 25, 'FontWeight', 'bold');
hold on
drawnow;
end
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.05, 1, 0.95]);
axis square;

Delshad Ayoubi
2018년 2월 22일
How can I plot the number of random walks and then see the steps they ALL take simultaneously? As it is now, my script plots the movement of one particle to N steps, then it takes another particle and continues this way M times. How can I immediately start with M particles active and see them take N steps instead of one by one?
Yo Seol
2021년 4월 1일
How would you do a 3D random walk with the code above?
Image Analyst
2021년 4월 2일
Just add a z variable and use plot3().
Andy Paulo Ureña
2022년 3월 1일
Hi, how can i calculate the distance from the origin to all points taken in every step iteration? Thanks a lot
@Andy Paulo Ureña make a new array called allDistances, and assign it distances
allDistances(n) = distance;
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
