Conditional sum on particular column of a matrix
3 views (last 30 days)
Show older comments
Surendra Kumar Singupalli
on 14 Apr 2015
Commented: Stephen23
on 18 Apr 2015
Dear all, I am trying to sum first 5 elements of column 1 of matrix m x n one after the other. Eg. say 1 2 3 4 5 6 then I want result as 1 3 6 10 15 21. After than I want to repeat the process again for m rows. Please help me with this. Regards, Suri
2 Comments
Stephen23
on 14 Apr 2015
Edited: Stephen23
on 14 Apr 2015
You write that you want "to sum first 5 elements", and then give an example with six elements. Do you want five or six elements? Or a general solution?
It is also not clear how the size of the matrix m*n relates to the number of rows that you are trying to sum: is m equal to five, or is m a multiple of five? Or is this relationship unknown?
Accepted Answer
Stephen23
on 14 Apr 2015
Edited: Stephen23
on 14 Apr 2015
>> A = bsxfun(@plus,(1:6).',[0,2,5,10])
A =
1 3 6 11
2 4 7 12
3 5 8 13
4 6 9 14
5 7 10 15
6 8 11 16
>> cumsum(A,1)
ans =
1 3 6 11
3 7 13 23
6 12 21 36
10 18 30 50
15 25 40 65
21 33 51 81
4 Comments
Stephen23
on 18 Apr 2015
Vectorized code would be neater and faster than trying to solve this in a loop. The simplest way would be to follow these steps:
- check if the number of rows is a multiple
- use an if conditional
- add one single zero to the last required row (the other rows will get filled automatically)
- perform the method that we defined above.
- trim the extra rows.
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!