Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for MATLAB for loop index

Tags:

I was surprised to find the following difference cost between running the MATLAB for loops:

ksize = 100;
klist = 1:ksize;

tic
for m = 1:100000        
    for k = 1:ksize

    end        
end
toc

tic
for m = 1:100000        
    for k = klist

    end        
end
toc

The only difference being the way the index list is created. I would have suspected the second version to be faster, but lo!

Elapsed time is 0.055400 seconds.
Elapsed time is 1.695904 seconds.

My question is twofold: what is responsible for the above result, and where else does this nuance (or similar ones) occur in MATLAB programming? I hope to be able to better spot these inefficiencies in the future. Thanks all.