user2105201
user2105201

Reputation: 15

Split a vector according to a defined sequence

Can anyone suggest a way in which it is possible to perform operations on a vector according to a predetermined sequence - for example I have a vector of different values, M, which is <8760x1> in size. I have another vector with a sequence of numbers, P, (size <300x1>) and this sequence sums to 8760. I would like to use these P values to index the vector M and find the product of each index.

An example to make this clearer:

M = [1,2,4,2,3,4,5,3,4,2];

P = [2,2,4,2];

Result = [3,6,15,6]

Any help here would be greatly appreciated.

Peter.S.

Upvotes: 1

Views: 157

Answers (1)

gevang
gevang

Reputation: 5014

Here is a way based on acummarray and a clever way to make an index vector using cumsum. Given the two vectors:

M = [1,2,4,2,3,4,5,3,4,2];
P = [2,2,4,2];

Create a vector of unique indices per frequency value in P (following this SO post):

numM = sum(P);
index = zeros(numM, 1);
index(cumsum([1 P(1:end-1)])) = 1;
index = cumsum(index);

>> index'
ans =
     1     1     2     2     3     3     3     3     4     4

Apply accumarray() using the constructed index vector and the vector of values:

result = accumarray(index, M);

>> result'
ans =
     3     6    15     6

Upvotes: 1

Related Questions