1

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.

  • 1
    I don't understand what you want to do. To use P as an index to M use M(P). That will give you [2, 2, 2, 2] in your example. Where does the product come from? – Molly Mar 24 '13 at 23:27
  • Apologies I have used the term index incorrectly. I wanted to find Result which gives the value of M(1,1)+M(1,2) =3, then M(1,3)+M(1,4) =6, then M(1,5)+M(1,6)+M(1,7)+M(1,8)=15 and M(1,9)+ M(1,10) =6. – user2105201 Mar 24 '13 at 23:39
  • The following codes can be used to solve this: 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) – user2105201 Mar 24 '13 at 23:47
  • You should add that as an answer and accept it so the question can be closed. – wakjah Mar 25 '13 at 22:23

1 Answers1

1

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
Community
  • 1
  • 1
gevang
  • 4,994
  • 25
  • 33