MATLAB: Partition vector in multiple parts using begin and end indices

1.2k views Asked by At

I have an 1xN array with data, from which I want to cut out the relevant parts. Basically I have two arrays - beginIndex and endIndex - that indicate which parts of data I need to extract.

Example:

data = 1:10;
beginIndex = [1 5 9];
endIndex = [3 6 10];

The desired result would be

partitionedData = [1 2 3 5 6 9 10] %Indices: 1-3, 5-6, 9-10 

I already tried

partitionedData = data(beginIndex:endIndex)

The latter gives me the equivalent to

partitionedData = data(beginIndex(1):endIndex(1)) %[1 2 3]

Also I tried accumarray, but the aggregation function must return scalar values. I would really appreciate some help here.

Thank you

2

There are 2 answers

2
Bas Swinckels On BEST ANSWER

Like so:

>> partitionedData = data(cell2mat(arrayfun(@(s,e) s:e, beginIndex, endIndex, ...
    'uni', 0)))
partitionedData =
     1     2     3     5     6     9    10
0
Luis Mendo On

In one line :-)

data(cell2mat(arrayfun(@(x,y) x:y, beginIndex,endIndex,'UniformOutput',false)))