MATLAB: Can you split a vector according to a pre-defined sequence

indexingsequencesplitvectors

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 < 8760×1 > in size. I have another vector with a sequence of numbers, P, (size < 300×1 >) 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.

Best Answer

M = [1,2,4,2,3,4,5,3,4,2];
P = [2,2,4,2];
id2=cumsum(P);
id1=[1 id2(1:end-1)+1];
for k=1:numel(id1)
Result(k)=sum(M(id1(k):id2(k)));
end
%or
id2=cumsum(P);
id1=[1 id2(1:end-1)+1];
Result=arrayfun(@(x,y) sum(M(x:y)),id1,id2)