-
5 Comments
Probably internal input/output argument checks. Multiply it via millions of iterations and you get significant difference. Your algorithm saves tons of time (in comparison) because you didn't bother to store all the steps, therefore you didn't fell into "dynamic indexing" trap which saves some steps, but drastically slows down the process during saving values to the main array.
I guess this is one of those times where saving the intermediate steps doesn't help your computation time. Nicely done. As a comparison, using mod(b,2) takes about two-thirds longer than 2*floor(b/2) on my machine; 18.8 sec vs 11.3 sec for n=1e8, and 38 sec vs 23 sec for 2e8. That's good to know for speeding things up in other codes I need to run millions of times!
mod(b,k) takes about 10x longer than b-k*floor(b/k) on my machine (2016b win64):
a = randi(1e7,1e8,1); m = 37;
tic, b = mod(a,m); toc;
tic, c = a - floor(a/m)*m; toc;
norm(b - c)
Elapsed time is 3.131306 seconds.
Elapsed time is 0.253768 seconds.
ans =
0
Suggested Problems
-
1028 Solvers
-
506 Solvers
-
Create a square matrix of multiples
482 Solvers
-
Make a run-length companion vector
644 Solvers
-
451 Solvers
More from this Author2
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!