I like the functional programming aspect of arrayfun (it clearly says: apply this function to all the elements of these sequence) but note that if speed is critical then an explicit loop is likely to be faster.
With arrayfun you don't have a choice but going through an intermediate cell array. With your example, you don't have to split it in two lines:
B = cell2mat(arrayfun(@(x,y) colon(x,y), A(1,:), A(2,:), 'UniformOutput', false));
With an explicit loop, in the case of your example you can easily calculate where the sequences land in the final array and avoid the cell array altogether:
seqlengths = A(2, :) - A(1, :) + 1;
seqstarts = cumsum([1, seqlengths(1:end-1)]);
B = zeros(1, seqstarts(end)-1);
for colidx = 1:size(A, 2)
B(seqstarts(colidx) + (0:seqlengths(colidx)-1)) = A(1, colidx) : A(2, colidx);
end
Whether the increase in code complexity is worth the gain is up to do. Of course the above may not work for your real use case.
Best Answer