Speed up for loops for arrays

Hello, Maybe someone could help me to speedup this type of for loop? I did try parfor, I did try to think of way using GPU, but it does not work with indexing.
clear;
a=7811200001;
d=1083355908;
c=zeros(1083355908,1)
parfor i = 1:d
c(i,1)=a+i;
end

 Accepted Answer

madhan ravi
madhan ravi on 9 Nov 2018
Edited: madhan ravi on 9 Nov 2018
a=7811200001;
d=1083355908;
c=a+(1:d);
c=(a+1):(a+d); %edited after jan's comment

10 Comments

This line
c=zeros(1083355908,1);
is completely superfluous and only slows the code down. Get rid of it.
Thank you @Stephen I thought it would enhance speed no?
Stephen23
Stephen23 on 9 Nov 2018
Edited: Stephen23 on 9 Nov 2018
"I thought it would enhance speed no?"
No. You simply created one large array in memory, and then on the next line created another large array in memory, that replaced the first array. It had nothing to do with preallocation, if that is what you were thinking, because you were not using indexing anywhere. Preallocation is where there is only one array (with its final size) in memory and its values are accessed using indexing: thus the array does not change size so it does not need to be moved in memory (not really relevant to your code) and its elements are simply accessed in situ using indexing (which is what you were not doing). Read the documentation and check how the examples use indexing:
Everything is clear now thank you
It might even slows down your code since it reduces a RAM for few subsequent instructions.
Useful info @Bruno
Stephen23
Stephen23 on 9 Nov 2018
Edited: Stephen23 on 9 Nov 2018
"It might even slows down your code ..."
Creating such a large array (which is entirely unused) will definitely slow down the code.
@madhan ravi: in any case, don't just believe me or Bruno because we wrote something: try it yourself! Use a loop and tic & toc, or use timeit, and find out yourself. Experimentation is always worthwhile.
@Stephen: sure!
Another hint: In a+(1:d) you create the double vector 1:d at first and then add a to each element. It is more efficient to omit the addition and create vector directly:
(a+1):(a+d)
madhan ravi
madhan ravi on 9 Nov 2018
Edited: madhan ravi on 9 Nov 2018
Selbverständlich , danke schön @Jan

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!