Reputation: 17
Hi I am working on my first random walk program. I was just able to figure out the random walk program itself. It is a simple 1d random walk, with 1000 steps. Here is what my code looks like so far:
stepslim = 1000;
rnew(1) = 0
r=0;
%Now we will set up the for loop
for isteps = 2:1:stepslim;
if rand <= 0.5 %The if-else statement will tell the walker
step = -1; %which direction it steps in
else
step = +1;
end
rnew(isteps) = rnew(isteps-1) + step; %This adds the new step
end
plot(rnew); %This will plot our random walk
This works just fine, and now I need to attempt a few more tasks:
Run this simulation X times to generate an ensemble. Record/store the final location of the walker at the end of each simulation in the ensemble.
Generate a histogram for the ending position of the walker for each simulation in the ensemble ▪ Adjust the bin-width to “make sense” of your results.
Repeat and plot results for X = [1000, 2000, 10000, 20000, 100000, 1000000]
I am not sure how to repeat the simulation and record the ending values into an ensemble. I would appreciate some help in accomplishing these tasks
Upvotes: 1
Views: 1384
Reputation: 23675
Your method for generating the random walks is very, very, very slow... if you want to change your approach, I would suggest you yo use the following code instead:
steps = 1000;
rw = cumsum(-1 + 2 * round(rand(steps,1)),1);
Starting from that point, here is how you could run your simulation x
times, record each result and retrieve the last step of every simulation:
iters = 10;
steps = 1000;
rws = NaN(steps,iters);
for i = 1:iters
rws(:,i) = cumsum(-1 + 2 * round(rand(steps,1)),1);
end
% retrieve the last step
last_steps = rws(end,:);
In order to plot an histogram of the last steps, you could use the histogram
function which should be flexible enough to print something coherent enough with your data:
histogram(last_steps);
To use different step sizes, just enclose everything inside another for loop
in which you cycle on every step size that you define within an array:
X = [1000, 2000, 10000, 20000, 100000, 1000000];
for j = 1:numel(X)
% previous code with variable "steps" replaced by X(j)
end
Upvotes: 1