Based on a matrix which contains several rows of the beginning (first column) and the end (second column) of an interval of index, I would like to create a vector of all the index. For instance, if A = [2 4; 8 11 ; 12 16]
, I would like to have the following vector index = [2 3 4 8 9 10 11 12 13 14 15 16]
.
I'm looking for the fastest way to do that. For now, I found only two possibilities:
1) with a loop
index = [];
for n = 1:size(A, 1)
index = [index A(n, 1):A(n, 2)];
end
2) with arrayfun
index = cell2mat(arrayfun(@(n) A(n, 1):A(n, 2), 1:size(A, 1), 'uni', 0));
Interestingly, arrayfun
is much faster than the loop version, and I don't know why. Plus I use a conversion from cell to mat, so that's weird. What do you think about that? Do you have another suggestions?
Thanx for your help
Hard to tell how fast that is, at least there is no looping:
Here is a collection of methods:
Method 1 from https://stackoverflow.com/a/39422485/6579744 :
Method 2: this is from https://stackoverflow.com/a/38507276/6579744 . I also provided the same answer but because Divakar's answer is before mine his (modified) answer preferred:
Method 3: this is mine
Method 4: another naswer from this thread by thewaywewalk
Method 5 your second method:
Method 6 from https://stackoverflow.com/a/39423102/6579744 :
Method 7 only works in Octave:
Method 8 your first method:
Test data:
Result tested in Octave, in Matlab may be different
the code that used in bechmark is in Online Demo