Conditional sum on particular column of a matrix

3 views (last 30 days)
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
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?
Surendra Kumar Singupalli
Surendra Kumar Singupalli on 14 Apr 2015
Hi Stephen,thanks for your message. Let me explain: I have a 1000 x 4 matrix. My aim is to add as you did below for every 5 elements per column (4 in total)up to 1000 elements. So for example matrix A; assume the sum window is 3 (not 5 as in my case) then it should look like this (column 1): 1 3 6 4 9 15 Am I clear this time? Thanks.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 14 Apr 2015
Edited: Stephen23 on 14 Apr 2015
You can use cumsum for this:
>> 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
Surendra Kumar Singupalli
Surendra Kumar Singupalli on 16 Apr 2015
Thanks Stephen. I followed this solution and it works for me. However, as you mentioned, if I have a dataset which is not multiple of variable N as above; it misses some of the day. Do we have a solution based on conditional loop may be?
Stephen23
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:
  1. check if the number of rows is a multiple
  2. use an if conditional
  3. add one single zero to the last required row (the other rows will get filled automatically)
  4. perform the method that we defined above.
  5. trim the extra rows.

Sign in to comment.

More Answers (0)

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!