Thang Luong Minh
Thang Luong Minh

Reputation: 29

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

Upvotes: 0

Views: 118

Answers (3)

Thang Luong Minh
Thang Luong Minh

Reputation: 29

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

Upvotes: 2

Q_1.0
Q_1.0

Reputation: 183

You may also try having some fun with matrices,

First get the difference between each entry and the first one in startIds,

dif = startIds - startIds(1);
dif_m = repmat(dif,endIds-startIds+1,1);

Then make a matrix of your first sequence

multi_seq = repmat((startIds(1):endIds(1))',1,length(startIds));

Get the sequences,

multi_seq = multi_seq + dif_m;

Upvotes: 1

scmg
scmg

Reputation: 1894

You can use arrayfun:

sequences = arrayfun(@(i, j) (i:j), startIds, endIds, 'un', 0);

You will get a cell array sequences, where sequences{k} = startIds(k):endIds(k).

Upvotes: 2

Related Questions