Search code examples
matlabfor-loopmatrixnested-forms

Summing specific columns for each row in a matrix of double


I would like to sum specific columns of each row in a matrix using a for loop. Below I have included a simplified version of my problem. As of right now, I am calculating the column sums individually, but this is not effective as my actual problem has multiple matrices (data sets).

a = [1 2 3 4 5 6; 4 5 6 7 8 9];
b = [2 2 3 4 4 6; 3 3 3 4 5 5];
% Repeat the 3 lines of code below for row 2 of matrix a
% Repeat the entire process for matrix b
c = sum(a(1,1:3));                   % Sum columns 1:3 of row 1
d = sum(a(1,4:6));                   % Sum columns 4:6 of row 1
e = sum(a(1,:));                     % Sum all columns of row 1

I would like to know how to create a for loop that automatically loops through and sums the specific columns of each row for each matrix that I have.

Thank you.


Solution

  • Here is a solution that you don't need to use for loop.

    Assuming that you have a matrix a of size 2x12, and you want to do the row sums every 4 columns, then you can use reshape() and squeeze() to get the final result:

    k = 4;
    a = [1:12
         13:24];
    % a =
    %    1    2    3    4    5    6    7    8    9   10   11   12
    %   13   14   15   16   17   18   19   20   21   22   23   24
    
    s = squeeze(sum(reshape(a,size(a,1),k,[]),2));
    

    and you will get

    s =
    
       10   26   42
       58   74   90