Search code examples
matlabmatrixcell-arraymatrix-indexing

Is there a built-in (no for loop) way to put ranges of a vector into a cell array using a matrix for the indices?


Given:

data = 0:10;
indices = [1 2; 3 7; 2 5];

Is there a one-line way to do this?:

for i = 1:length(indices)
    out{i} = data(indices(i,1):indices(i,2))
end

Solution

  • You can do this with arrayfun:

    out = arrayfun(@(a,b) data(a:b), indices(:,1), indices(:,2), 'UniformOutput', false);
    

    However, internally arrayfun is still probably just using a for loop, so I wouldn't expect to see any improvement in speed. This syntax simply allows you to write it as a one-liner. A somewhat ugly one-liner.