How do I loop inside a loop for a random walk? How to store values inside the loop?

I have attached the file that contains the original question. I have already mapped a 1-d random walk of 1000 steps. Now I need to record the value of every 10 step and then plot the graph with these values. How do I store these values in a loop? To generate these seperate values, do I introduce new variables? And to plot the graph, which variables do I use? This is what I have done so far. The first section of the for loop is what I used to create a random walk of a 1000 steps previously. I have included %notes to provide questions about why I am confused. Thanks in advance to anyone who is kind enough to help.
n=1000; % Number of steps
P=(1:n); % P represents the random position
P(1)=0; % Starting point of the walk is set to be zero
for i=2:n; % i represents the steps from the second step till n=1000
R=rand % R generates the random number between 0 and 1
if R<0.5 % To generate -1
S=-1;
elseif R>0.5 % To generate +1
S=1;
end
P(i)=S+P(i-1); % Position at i(the number of the step at the current position) plus the random number to give the new position
Q=(10:10:1000) % What should I put to determine position of every 10 step like I did previously as in P=(1:n)
for j=(10:10:1000) %What to put for j? Or should I keep i to determine the number of steps?
R=rand % Do I repeat this? If I do, how can I make sure this rand value is the same one used with P? (seems impossible so I think I am doing this wrong)
if R<0.5
S=-1;
elseif R>0.5
S=1;
end
Q(j)=S+Q(j-1); % No idea what to do here to give me a value for the 10th step every time and how to hold it
end
end
plot(Q,10:10:1000,'Linestyle','*') % How do I plot the graph with * marks marking the final position?
xlabel('Final Position')
ylabel('Frequency')
title('Frequency to Final Position (10 steps)')

回答(1 个)

According to my understanding, you have already generated all of your steps in vector P (length = 1000). So what you have to do is to eliminate all of the stuff after P(i) = S+P(i-1) within the big "for loop". Then add another variable Q to extract the value from P outside of your for loop.
Q = P(10:10:1000)
This will extract the elements in P with a step size of 10, and the length of Q will be 100 (ie. you store the value in Q every 10 step)
Hope it helps

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by