Finding if a random walk "hits" a target in two dimensions

4 次查看(过去 30 天)
Hi! I have the following code. x and y describe positions in a 2D lattice, and I have a random walk that loops to make a walker walk around the lattice. I have a target that is randomly defined, and I'm looking to read out if the walker visits the target at any point during it's random walk. A walk consists of N steps, and the simulation is run M times. I was able to do this in 1D, but reading out if the target has been hit is giving me issues in 2D.
B = ([x,y]==Target);
F= sum(B(:)==1);
results=results+F
end
This is at the end of a pretty large for loop that runs ii:10000
For reference, it looks like this in 1D. It's not pretty, but it's getting the job done.
if D==1 %if in one dimension
for j=1:num_walk %runs num_walk number of simulation
for i=1:num_steps
step = rand; %assigns random value between 0 and 1
if step<0.5 %prob of +1 step
x(i+1)=x(i)+1;
if x(i+1) == N %makes sure walker does not go outside of boundaries
x(i+1)=x(i)-1;
end
else
x(i+1)=x(i)-1; %prob -1 step
if x(i+1) == N %makes sure walker does not go outside of boundaries
x(i+1)=x(i)+1;
end
end
end
B = x==Target;
F= sum(B(:)==1);
results=results+F
end
plot(x) %plot walk
end
  1 个评论
James Tursa
James Tursa 2017-2-9
I cleaned up your indenting. You should really learn to do this with your code since if greatly improves the ability to read and debug your code.

请先登录,再进行评论。

采纳的回答

James Tursa
James Tursa 2017-2-9
编辑:James Tursa 2017-2-9
For 2D I assume you have x and y vectors that you are building at each step, and that Target is a 2-element vector with an x and y position that is fixed. For that case, you need to alter your test to see if you hit the Target. Also, it appears you want "results" to be the number of times you hit the Target. So you could use this instead, outside the loop next to the plot statement:
results = sum(x==Target(1) & y==Target(2));
And for your 1D case, you could do the similar thing (again outside the loop):
results = sum(x==Target);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by