How can I make this code more efficient so it will run faster?
Show older comments
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
More Answers (0)
Categories
Find more on Design Condition Indicators Interactively in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!