matlab - Adding up different number of elements from each row -


i have main matrix, say

a=magic(5); 

and vector

v=[1;3;5;2;2]; 

i want add row-wise elements of in way: add first row v(1)st element end, second row v(2)rd element end, third row v(3)th element end, , on.

i know can using for-loop. want know if there vectorized way it.

edit: let me clarify question example: assume , v above.

a =   17    24     1     8    15  23     5     7    14    16   4     6    13    20    22  10    12    19    21     3  11    18    25     2     9 

and

v =   1  3  5  2  2 

now want way following results:

answer =  65  % 17+24+1+8+15  37  % 7+14+16  22  % 22  55  % 12+19+21+3  54  % 18+25+2+9 

you can use cumsum along rows. solution bit complex, i'll start simpler example:

suppose want sum elements of i-th row of a till (including) v(i)-th place: res_i = \sum_{k=1..v(i)} a_ik

m = size(a,1); % num of rows csa = cumsum(a, 2); % cumsum along rows res = csa( sub2ind( size(a), 1:m, v ) ); % pick vi-th column i-th row 

now, question, since want sum of elements from v(i) end, need flip a , change v accordingly

[m n] = size(a); fa = fliplr(a); fv = n + 1 - v; % flip meaning of v csa = cumsum( fa, 2 );  res = csa( sub2ind( [m n], 1:m, fv ) ); % should trick... 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -