How can I make this code more efficient so it will run faster?

14 views (last 30 days)
Hello, I am currently working on a coding assignment that wants me to track a walking person for 2500 steps while using a random number generator between 1 and 2 to determine if the walker steps left or right for each step. Furthermore, I am supposed to run the simulation for X amount of times (X = [1000, 2500, 10000, 25000, 100000, 1000000]), effectively creating 6 "ensembles." I am then supposed to record the final location of the walker at the end of each simulation, and then generate a histogram composed of the ending positions for each ensemble. Now I have already come up with my own code, and it outputs 5 of the 6 necessary histograms (which I assume are correct). However, it will often take 20+ minutes to actually output anything and even then it doesn't fully run to completion for some reason. Here is my code:
% 1 = step left
% 2 = step right
X = [1000, 2500, 10000, 25000, 100000, 1000000] ;
for k = 1:length(X)
Final = zeros(1,X(k)) ;
for j = 1:X(k)
for i = 1:2500
W = randi(2) ;
if W == 1 % Left
Final(j) = Final(j) - 1 ;
else % Right
Final(j) = Final(j) + 1 ;
end
end
end
figure
histogram(Final,50)
end

Accepted Answer

Tommy
Tommy on 16 Apr 2020
Since the order of the steps doesn't matter, how about this?
X = [1000, 2500, 10000, 25000, 100000, 1000000];
for k = 1:length(X)
Final = zeros(1,X(k));
for j = 1:X(k)
W = randi(2,2500,1); % generate all 2500 steps at once
Final(j) = sum(W==2) - sum(W==1); % 2s are forwards, 1s are backwards
end
figure
histogram(Final,50)
drawnow
end

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!