Search code examples
matlabfor-loopsequences

Fast ways to generate multiple sequences without using for loop in Matlab


Suppose, I have two arrays:

startIds = [x1, x2, x3]
endIds = [y1, y2, y3]

The two arrays have the same length and can be long. We may assume that (endIds(ii)-startIds(ii)) are the same for all positions ii. Is there any fast ways to generate multiple sequences without using for loop?

startIds(1):endIds(1)
startIds(2):endIds(2)
startIds(3):endIds(3)

Thanks!

-Thang


Solution

  • Here's the fastest answer I got through Mathworks:

    range = endIds(1) - startIds(1);
    t3 = bsxfun(@plus, startIds(:), 0:range);
    

    At the time of this writing, this is the only version that is faster than my for loop version, which is in turn faster than using arrayfun or ndgrid. See my detailed benchmark here: http://www.mathworks.com/matlabcentral/answers/217205-fast-ways-to-generate-multiple-sequences-without-using-for-loop