2

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
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • 2
    An extra tip: as per [this Documentation page](http://stackoverflow.com/documentation/matlab/973/common-mistakes-and-errors/27689/using-length-for-multidimensional-arrays#t=201703292057296513663), you want to be using the `size` function instead of the `length` function. – gnovice Mar 29 '17 at 21:01
  • Agreed - I recently got bit by that, but haven't changed my habit yet. – user2149714 Mar 30 '17 at 00:52

2 Answers2

3

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.

gnovice
  • 125,304
  • 15
  • 256
  • 359
  • I kind-of figured it wouldn't be as neat as I hoped. And I definitely didn't expect a performance improvement. But this taught me a new tool, which is valuable. Thanks. – user2149714 Mar 29 '17 at 21:06
1

The following is on

out = arrayfun(@(ii)data(indices(ii,1):indices(ii,2)),1:size(indices,1),'UniformOutput',false)
mikado
  • 201
  • 1
  • 8