Four different outputs keep ending up with the same "answer" when I don't believe they're supposed to.

1 view (last 30 days)
Kristin Aldridge
Kristin Aldridge on 3 Oct 2021
Answered: DGM on 3 Oct 2021
I am trying to plot the path of 1 particle for 100 steps, running 100 runs, with the option for it to go up,down,left, or right randomly. I want to find the root mean square distance (square root of the number of steps) and final position. My distance, distances, rootmeansquared, and meandistance all keep coming up as the same value and I'm not sure why. Any help is appreciated.
Homework question: Write a simulation of a random walk in two dimensions, in which the particle stands at an intersection and chooses to go left, right, up, or down. The average final position is zero, and the root mean squared distance is the square root of the number of steps. Try it with 100 steps and with 1000 steps, and run the simulation 100 times. Make sure that the final position and root mean square distance are what you expect. Show a plot of the particle’s path for each run of the simulation.
pos=[0 0]
distances= [ ]
coinx = 0
coiny = 0
figure
for j=1:1
for i=1:100
coinx=rand;
coiny=rand;
if coinx>0.5
pos(1)=pos(1)+1;
else
pos(1)=pos(1)-1;
end
if coiny>0.5
pos(2)=pos(2)+1;
else
pos(2)=pos(2)-1;
end
plot(pos(1),pos(2),'ro');
hold on
end
distance=sqrt(pos(1)^2+sqrt(pos(2)^2))
distances=[distances distance]
hold on
pos=[0 0];
end
rootmeansquared=rms(distances)
meandist=mean(distances) %This is the final position
Thank you.
  2 Comments
Kristin Aldridge
Kristin Aldridge on 3 Oct 2021
I'm having trouble finding how to log the x and y positions. Below is what I came up with but I'm missing what to put in the code itself, and where. I've been trying pos1(end) and pos2(end) and then having empty vectors for pos1(end)=[ ] and pos2(end)=[ ] but it keeps telling me "The end operator must be used within an array index expression".

Sign in to comment.

Accepted Answer

DGM
DGM on 3 Oct 2021
Something like this:
numsteps = 100;
numtrials = 10;
distances = zeros(numtrials,1);
finalpos = zeros(numtrials,2);
for j = 1:numtrials
pos = [0 0];
for i = 1:numsteps
% this does the same as the if statements
pos = pos + 2*round(rand(1,2)) - 1;
plot(pos(1),pos(2),'ro');
hold on
end
distances(j) = sqrt(pos(1)^2+sqrt(pos(2)^2)); % this doesn't look right
finalpos(j,:) = pos; % store final position
end
rootmeansquared = rms(distances)
meandist = mean(finalpos,1) % This is the mean end position
I'm not really sure what the requirements actually are here. It kind of sounds like you're supposed to get the RMS distance estimate, which would just be sqrt(N) -- which is something that's known from the start.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by